$(document).ready(function() {
    var $url = $('body').attr('data-siteurl');
    var date = new Date();
    var yr = date.getFullYear();
    var mon = date.getMonth() + 1;
    var month;
    if (mon.toString().length > 1) {
        month = mon;
    } else {
        month = '0' + mon;
    }
//My Account--------------------------------------------------------------------
    //Edit profile
    $('.btn-edit-acc-profile').click(function() {
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'my-account/get',
            type: 'post',
            dataType: 'json',
            success: function(data) {
                var g = '';
                var address = data.account.coord_address.split(';');
                var email = data.account.coord_email.split(';');
                var contact = data.account.coord_num.split(';');
                if (data.account.coord_gender == '0') {
                    g = '<label class="btn btn-default active"><input type="radio" name="gender" value="0" checked>Male' +
                            '</label><label class="btn btn-default"><input type="radio" name="gender" value="1">Female</label>';
                } else {
                    g = '<label class="btn btn-default"><input type="radio" name="gender" value="0">Male</label>' +
                            '<label class="btn btn-default active"><input type="radio" name="gender" value="1" checked>Female</label>';
                }
                if (data.status == 'success') {
                    $('.btn-browse-profile-pic').removeClass('hide');
                    $('.upload-profile-pic-container').addClass('hide');
                    $('#my-account-container #userfile').val('');
                    $('.profile-pic-path').val('');
                    $('.edit-account-profile #account-details-form').append('<input type="hidden" id="emp-id" value="' + data.account.coordinator_id + '" /><div class="form-group">' +
                            '<label class="col-md-4 my-acc-label">Last Name</label>' +
                            '<div class="col-md-8">' +
                            '<input type="text" class="form-control lname" name="lname" value="' + data.account.coord_lname + '"/>' +
                            '</div>' +
                            '</div>' +
                            '<div class="form-group">' +
                            '<label class="col-md-4 my-acc-label">First Name</label>' +
                            '<div class="col-md-8">' +
                            '<input type="text" class="form-control fname" name="fname" value="' + data.account.coord_fname + '"/>' +
                            '</div>' +
                            '</div>' +
                            '<div class="form-group">' +
                            '<label class="col-md-4 my-acc-label">Middle Name</label>' +
                            '<div class="col-md-8">' +
                            '<input type="text" class="form-control mname" name="mname" value="' + data.account.coord_mname + '"/>' +
                            '</div>' +
                            '</div>' +
                            '<div class="form-group">' +
                            '<label class="col-md-4 my-acc-label">Birthday</label>' +
                            '<div class="col-md-8">' +
                            '<input type="text" class="form-control bday" name="bday" value="' + data.account.coord_bday + '">'+
                            '</div>' +
                            '</div>' +
                            '<div class="form-group">' +
                            '<label class="col-md-4 my-acc-label">Gender</label>' +
                            '<div class="col-md-8">' +
                            '<div class="btn-group gender" data-toggle="buttons">' +
                            g +
                            '</div>' +
                            '</div>' +
                            '</div>' +
                            '<div class="form-group">' +
                            '<label class="col-md-4">Home Address</label>' +
                            '<div class="col-md-8 address-container">' +
                            '<a class="add-a-row">Add row</a>'+
                            '<input type="text" class="form-control acc-address address-1" name="address_1">' +
                            '<div class="input-group">'+
                            '<input type="text" class="form-control acc-address address-2" name="address_2">' +
                            '<span class="input-group-btn">'+
                            '<button class="btn btn-default btn-remove-row" type="button" title="Remove Row"><span class=" glyphicon glyphicon-remove"></span></button>'+
                            '</span>'+
                            '</div>'+
                            '<div class="input-group">'+
                            '<input type="text" class="form-control acc-address address-3" name="address_3">' +
                            '<span class="input-group-btn">'+
                            '<button class="btn btn-default btn-remove-row" type="button" title="Remove Row"><span class=" glyphicon glyphicon-remove"></span></button>'+
                            '</span>'+
                            '</div>'+
                            '</div>' +
                            '</div>' +
                            '</div>' +
                            '<div class="form-group">' +
                            '<label class="col-md-4 my-acc-label">Contact No.</label>' +
                            '<div class="col-md-8 contact-container">' +
                            '<div class="input-group">' +
                            '<a class="add-c-row">Add row</a>'+
                            '<input type="text" class="form-control acc-contact contact-1" name="contact_1">' +
                            '<div class="input-group">'+
                            '<input type="text" class="form-control acc-contact contact-2" name="contact_2">' +
                            '<span class="input-group-btn">'+
                            '<button class="btn btn-default btn-remove-row" type="button" title="Remove Row"><span class=" glyphicon glyphicon-remove"></span></button>'+
                            '</span>'+
                            '</div>'+
                            '<div class="input-group">'+
                            '<input type="text" class="form-control acc-contact contact-3" name="contact_3">' +
                            '<span class="input-group-btn">'+
                            '<button class="btn btn-default btn-remove-row" type="button" title="Remove Row"><span class=" glyphicon glyphicon-remove"></span></button>'+
                            '</span>'+
                            '</div>'+
                            '</div>' +
                            '</div>' +
                            '</div>' +
                            '<div class="form-group">' +
                            '<label class="col-md-4">Email Address</label>' +
                            '<div class="col-md-8 email-container">' +
                            '<a class="add-e-row">Add row</a>'+
                            '<input type="text" class="form-control acc-email email-1" name="email_1">' +
                            '<div class="input-group">'+
                            '<input type="text" class="form-control acc-email email-2" name="email_2">' +
                            '<span class="input-group-btn">'+
                            '<button class="btn btn-default btn-remove-row" type="button" title="Remove Row"><span class=" glyphicon glyphicon-remove"></span></button>'+
                            '</span>'+
                            '</div>'+
                            '</div>' +
                            '</div>' +
                            '</div>' +
                            '<div class="text-right">' +
                            '<button type="button" class="btn btn-default btn-cancel-acc-profile">Cancel</button> ' +
                            '<button type="submit" class="btn btn-primary btn-update-acc-profile">Update</button>' +
                            '</div>');
                    $('.edit-account-profile .bday').datepicker({
                        autoclose: true,
                        format: "yyyy-dd-mm",
                    });
                    if(typeof address[0]==='undefined'){
                        $('.edit-account-profile #account-details-form .address-container .address-1').parent().addClass('hide');
                    }else{
                        $('.edit-account-profile #account-details-form .address-container .address-1').val(address[0]);
                    }
                    if(typeof address[1]==='undefined'){
                        $('.edit-account-profile #account-details-form .address-container .address-2').parent().addClass('hide');
                    }else{
                        $('.edit-account-profile #account-details-form .address-container .address-2').val(address[1]);
                    }
                    if(typeof address[2]==='undefined'){
                        $('.edit-account-profile #account-details-form .address-container .address-3').parent().addClass('hide');
                    }else{
                        $('.edit-account-profile #account-details-form .address-container .address-3').val(address[2]);
                    }
                    if(typeof email[0]==='undefined'){
                        $('.edit-account-profile #account-details-form .email-container .email-').parent().addClass('hide');
                    }else{
                        $('.edit-account-profile #account-details-form .email-container .email-1').val(email[0]);
                    }
                    if(typeof email[1]==='undefined'){
                        $('.edit-account-profile #account-details-form .email-container .email-2').parent().addClass('hide');
                    }else{
                        $('.edit-account-profile #account-details-form .email-container .email-2').val(email[1]);
                    }
                    if(typeof contact[0]==='undefined'){
                        $('.edit-account-profile #account-details-form .contact-container .contact-1').parent().addClass('hide');
                    }else{
                        $('.edit-account-profile #account-details-form .contact-container .contact-1').val(contact[0]);
                    }
                    if(typeof contact[1]==='undefined'){
                        $('.edit-account-profile #account-details-form .contact-container .contact-2').parent().addClass('hide');
                    }else{
                        $('.edit-account-profile #account-details-form .contact-container .contact-2').val(contact[1]);
                    }
                    if(typeof contact[2]==='undefined'){
                        $('.edit-account-profile #account-details-form .contact-container .contact-3').parent().addClass('hide');
                    }else{
                        $('.edit-account-profile #account-details-form .contact-container .contact-3').val(contact[2]);
                    }
                    
                    $('.btn-change-pass').addClass('hide');
                    $('.btn-update-acc-profile').removeClass('hide');
                    $('.btn-cancel-acc-profile').removeClass('hide');
                    $('.btn-edit-acc-profile').addClass('hide');
                    $('.view-account-profile').addClass('hide');
                    $('.edit-account-profile').removeClass('hide');
                    $('.loading-container').addClass('hide');
                } else {
                    $('.alert-danger').remove();
                    $('.alert-success').remove();
                    $('#my-account-container .page-header').after('<div class="alert alert-danger">Something went wrong while fetching account profile. Please try again later.</div>');
                    error_msg();
                    $('.loading-container').addClass('hide');
                }
            },
            error: function() {
                $('.alert-danger').remove();
                $('.alert-success').remove();
                $('#my-account-container .page-header').after('<div class="alert alert-danger">Something went wrong while fetching account profile. Please try again later.</div>');
                error_msg();
                $('.loading-container').addClass('hide');
            }
        });
    });
    $('.edit-account-profile').on('click', '.add-a-row', function() {
        if($('.edit-account-profile .address-container .address-1').parent().hasClass('hide')){
            $('.edit-account-profile .address-container .address-1').parent().removeClass('hide');
        }else if($('.edit-account-profile .address-container .address-2').parent().hasClass('hide')){
            $('.edit-account-profile .address-container .address-2').parent().removeClass('hide');
        }else if($('.edit-account-profile .address-container .address-3').parent().hasClass('hide')){
            $('.edit-account-profile .address-container .address-3').parent().removeClass('hide');
        }
    });
    $('.edit-account-profile').on('click', '.address-container .btn-remove-row', function() {
        $(this).parent().siblings().val('');
        $(this).parent().parent().addClass('hide');
    });
    $('.edit-account-profile').on('click', '.add-e-row', function() {
        if($('.edit-account-profile .email-container .email-1').parent().hasClass('hide')){
            $('.edit-account-profile .email-container .email-1').parent().removeClass('hide');
        }else if($('.edit-account-profile .email-container .email-2').parent().hasClass('hide')){
            $('.edit-account-profile .email-container .email-2').parent().removeClass('hide');
        }
    });
    $('.edit-account-profile').on('click', '.email-container .btn-remove-row', function() {
        $(this).parent().siblings().val('');
        $(this).parent().parent().addClass('hide');
    });
    $('.edit-account-profile').on('click', '.add-c-row', function() {
        if($('.edit-account-profile .contact-container .contact-1').parent().hasClass('hide')){
            $('.edit-account-profile .contact-container .contact-1').parent().removeClass('hide');
        }else if($('.edit-account-profile .contact-container .contact-2').parent().hasClass('hide')){
            $('.edit-account-profile .contact-container .contact-2').parent().removeClass('hide');
        }else if($('.edit-account-profile .contact-container .contact-3').parent().hasClass('hide')){
            $('.edit-account-profile .contact-container .contact-3').parent().removeClass('hide');
        }
    });
    $('.edit-account-profile').on('click', '.contact-container .btn-remove-row', function() {
        $(this).parent().siblings().val('');
        $(this).parent().parent().addClass('hide');
    });
    $('.edit-account-profile').on('click', '.btn-cancel-acc-profile', function() {
        $('.view-account-profile').removeClass('hide');
        $('.edit-account-profile #account-details-form').empty();
        $('.btn-change-pass').removeClass('hide');
        $('.btn-edit-acc-profile').removeClass('hide');
        $('.btn-update-acc-profile').removeClass('hide');
    });
    $('.btn-browse-profile-pic').click(function() {
        $(this).addClass('hide');
        $('.upload-profile-pic-container').removeClass('hide');
        $('.view-account-profile').removeClass('hide');
        $('.edit-account-profile #account-details-form').empty();
        $('.btn-change-pass').removeClass('hide');
        $('.btn-edit-acc-profile').removeClass('hide');
        $('.btn-update-acc-profile').removeClass('hide');
        $('.change-pass-container').addClass('hide');
        $('.view-account-profile').removeClass('hide');
        $('.btn-change-pass').removeClass('hide');
        $('.btn-edit-acc-profile').removeClass('hide');
        $('.change-pass-container .btn-update-password').attr('disabled', true);
    });
    $('.btn-cancel-profile-pic').click(function() {
        $('.btn-browse-profile-pic').removeClass('hide');
        $('.upload-profile-pic-container').addClass('hide');
        $('#my-account-container #userfile').val('');
        $('.profile-pic-path').val('');
    });
    $('.btn-open-profile-pic').click(function() {
        $('#my-account-container #profile-pic-file').click();
    });
    $('#my-account-container').on('change', '#profile-pic-file', function() {
        $('.profile-pic-path').val($(this).val());
    });
    $('.btn-upload-profile-pic').click(function() {
        $('.loading-container').removeClass('hide');
        $.ajaxFileUpload({
            url: $url + 'my-account/upload',
            secureuri: false,
            fileElementId: 'profile-pic-file',
            dataType: 'json',
            success: function(data, status) {
                if (data.status === 'success') {
                    $('.btn-browse-profile-pic').removeClass('hide');
                    $('.upload-profile-pic-container').addClass('hide');
                    $('#my-account-container #userfile').val('');
                    $('.profile-pic-path').val('');
                    $('#my-account-container .profile-pic-image').attr('src', $url + data.image);
                    $('.btn-browse-profile-pic').parent().before('<p class="margin-top success-msg">' + data.msg + '</p>');
                    success_msg();
                    $('.loading-container').addClass('hide');
                } else {
                    $('#my-account-container .upload-profile-pic-container .input-group').after('<p class="required-error">' + data.msg + '</p>');
                    $('#my-account-container #profile-pic-file').val('');
                    $('.profile-pic-path').val('');
                    $('.loading-container').addClass('hide');
                    error_msg();
                }
            },
            error: function() {
                $('.alert-danger').remove();
                $('.alert-success').remove();
                $('#my-account-container .page-header').after('<div class="alert alert-danger">Something went wrong while uploading profile picture. Please try again later.</div>');
                error_msg();
                $('.loading-container').addClass('hide');
            }
        });
    });
    $('.edit-account-profile #account-details-form').validate({
        rules: {
            lname: 'required',
            fname: 'required',
            mname: 'required',
            bday: {
                'required': true,
                'date': true
            },
            address_1: 'required',
            email_1: {
                required: true,
                email: true,
            },
            email_2: 'email',
            contact_1: {
                required: true,
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
            contact_2: {
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
            contact_3: {
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
        },
        
        errorPlacement: function(error, element){
            var name = element.prop('name');
            if(name==='address_1'){
                $('.edit-account-profile .address-container .address-1').after(error);
            }else if(name==='contact_1'){
                $('.edit-account-profile .contact-container .contact-1').after(error);
            }else if(name==='contact_2'){
                $('.edit-account-profile .contact-container .contact-2').parent().after(error);
            }else if(name==='contact_3'){
                $('.edit-account-profile .contact-container .contact-3').parent().after(error);   
            }else if(name==='email_1'){
                $('.edit-account-profile .email-container .email-1').parent().after(error);   
            }else if(name==='email_2'){
                $('.edit-account-profile .email-container .email-2').parent().after(error);   
            }
        },
        submitHandler: function(form) {
            var address = new Array();
            var email = new Array();
            var contact = new Array();
            $('.edit-account-profile #account-details-form .address-container .acc-address').each(function() {
                if ($(this).val() != '') {
                    address.push($(this).val());
                }
            });
            $('.edit-account-profile #account-details-form .email-container .acc-email').each(function() {
                if ($(this).val() != '') {
                    email.push($(this).val());
                }
            });
            $('.edit-account-profile #account-details-form .contact-container .acc-contact').each(function() {
                if ($(this).val() != '') {
                    contact.push($(this).val());
                }
            });
            var acc = {
                'lname': $('.edit-account-profile #account-details-form .lname').val(),
                'fname': $('.edit-account-profile #account-details-form .fname').val(),
                'mname': $('.edit-account-profile #account-details-form .mname').val(),
                'bday': $('.edit-account-profile #account-details-form .bday').val(),
                'gender': $('.edit-account-profile #account-details-form .gender .active input').val(),
                'address': address.join(';'),
                'email': email.join(';'),
                'contact_no': contact.join(';'),
            };
            $('.loading-container').removeClass('hide');
            $.ajax({
                url: $url + 'my-account/update',
                type: 'post',
                data: acc,
                dataType: 'json',
                success: function(data){
                    if(data.status==='success'){
                        $('.alert').remove();
                        $('#my-account-container .page-header').after('<div class="alert alert-success">'+data.msg+'</div>');
                        remove_alert();
                        var g = '';
                        if (acc.gender == '0') {
                            g = 'Male';
                        } else {
                            g = 'Female';
                        }
                        $('.view-account-profile .name').text(acc.lname + ', ' + acc.fname + ' ' + acc.mname);
                        $('.view-account-profile .bday').text(acc.bday);
                        $('.view-account-profile .gender').text(g);
                        $('.view-account-profile .address').text(acc.address);
                        $('.view-account-profile .email').text(acc.email);
                        $('.view-account-profile .contact').text(acc.contact_no);
                        $('.view-account-profile').removeClass('hide');
                        $('.edit-account-profile #account-details-form').empty();
                        $('.btn-change-pass').removeClass('hide');
                        $('.btn-edit-acc-profile').removeClass('hide');
                        $('.loading-container').addClass('hide');
                    }else{
                        $('.alert').remove();
                        $('#my-account-container .page-header').after('<div class="alert alert-warning">'+data.msg+'</div>');
                        remove_alert();
                        $('.loading-container').addClass('hide');
                    }
                },
                error: function(xhr, status){
                    $('.alert').remove();
                    $('#my-account-container .page-header').after('<div class="alert alert-danger">Something went wrong while performing changes to your account. Please try again later.</div>');
                    remove_alert();
                    $('.loading-container').addClass('hide');
                }
            });
            return false;
        }
    });
    // Change password
    $('.btn-change-pass').click(function() {
        $('.view-account-profile').addClass('hide');
        $('.change-pass-container').removeClass('hide');
        $(this).addClass('hide');
        $('.btn-edit-acc-profile').addClass('hide');
        $('.btn-update-password').removeClass('hide');
        $('.btn-cancel-change-pass').removeClass('hide');
        $('.change-pass-container .old-pass').val('');
        $('.change-pass-container .new-pass').val('');
        $('.change-pass-container .confirm-pass').val('');
        $('.change-pass-container .invalid-old-pass').remove();
        $('.change-pass-container .pass-no-match').remove();
        $('.btn-browse-profile-pic').removeClass('hide');
        $('.upload-profile-pic-container').addClass('hide');
        $('#my-account-container #userfile').val('');
        $('.profile-pic-path').val('');
    });
    $('.btn-cancel-change-pass').click(function() {
        $('.change-pass-container').addClass('hide');
        $('.view-account-profile').removeClass('hide');
        $('.btn-change-pass').removeClass('hide');
        $('.btn-edit-acc-profile').removeClass('hide');
        $('.change-pass-container .btn-update-password').attr('disabled', true);
    });
    $('.change-pass-container .old-pass').change(function() {
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'my-account/old-pass',
            type: 'post',
            data: {'old_pass': $(this).val()},
            success: function(data) {
                if (data == 'invalid') {
                    if (!$('.change-pass-container p').hasClass('invalid-old-pass')) {
                        $('.change-pass-container .old-pass').after('<p class="required-error invalid-old-pass">Invalid password</p>');
                    }
                    $('.change-pass-container .btn-update-password').attr('disabled', true);
                    $('.loading-container').addClass('hide');
                } else if (data == 'valid') {
                    $('.change-pass-container').find('.invalid-old-pass').remove();
                    if ($('.change-pass-container .confirm-pass').val() != '' &&
                            $('.change-pass-container .confirm-pass') != '' &&
                            !$('.change-pass-container').hasClass('pass-no-match')) {
                        $('.change-pass-container .btn-update-password').attr('disabled', false);
                        $('.loading-container').addClass('hide');
                    } else {
                        $('.change-pass-container .btn-update-password').attr('disabled', true);
                        $('.loading-container').addClass('hide');
                    }
                }
            },
            error: function() {
                $('.change-pass-container').find('.invalid-old-pass').remove();
                $('.change-pass-container .old-pass').after('<p class="required-error invalid-old-pass">Sorry something' +
                        ' went wrong while validating your old password. Please try again.</p>');
                $('.loading-container').addClass('hide');
            }
        });
    });
    $('.change-pass-container .new-pass').change(function() {
        if ($(this).val() != $('.change-pass-container .confirm-pass').val()) {
            if (!$('.change-pass-container p').hasClass('pass-no-match')) {
                $('.change-pass-container .confirm-pass').after('<p class="required-error pass-no-match">Password do not match.</p>');
            }
            $('.change-pass-container .btn-update-password').attr('disabled', true);
        } else {
            $('.change-pass-container').find('.pass-no-match').remove();
            if (!$('.change-pass-container').hasClass('invalid-old-pass') &&
                    $('.change-pass-container .old-pass').val() != '') {
                $('.change-pass-container .btn-update-password').attr('disabled', false);
            }
        }
    });
    $('.change-pass-container .confirm-pass').change(function() {
        if ($(this).val() != $('.change-pass-container .new-pass').val()) {
            if (!$('.change-pass-container p').hasClass('pass-no-match')) {
                $('.change-pass-container .confirm-pass').after('<p class="required-error pass-no-match">Password do not match.</p>');
            }
            $('.change-pass-container .btn-update-password').attr('disabled', true);
        } else {
            $('.change-pass-container').find('.pass-no-match').remove();
            if (!$('.change-pass-container').hasClass('invalid-old-pass') &&
                    $('.change-pass-container .old-pass').val() != '') {
                $('.change-pass-container .btn-update-password').attr('disabled', false);
            }
        }
    });
    $('.change-pass-container .btn-update-password').click(function() {
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'my-account/change-pass',
            type: 'post',
            data: {'confirm_pass': $('.change-pass-container .confirm-pass').val()},
            dataType: 'json',
            success: function(data) {
                if (data.status == 'success') {
                    $('.alert-danger').remove();
                    $('.alert-success').remove();
                    $('#my-account-container .page-header').after('<div class="alert alert-success">' + data.msg + '</div>');
                    $('.change-pass-container').addClass('hide');
                    $('.view-account-profile').removeClass('hide');
                    $('.btn-change-pass').removeClass('hide');
                    $('.btn-edit-acc-profile').removeClass('hide');
                    $('.change-pass-container .btn-update-password').attr('disabled', true);
                    success_msg();
                    $('.loading-container').addClass('hide');
                } else {
                    $('.alert-danger').remove();
                    $('.alert-success').remove();
                    $('#my-account-container .page-header').after('<div class="alert alert-danger">' + data.msg + '</div>');
                    error_msg();
                    $('.loading-container').addClass('hide');
                }
            },
            error: function() {
                $('.alert-danger').remove();
                $('.alert-success').remove();
                $('#my-account-container .page-header').after('<div class="alert alert-danger">Something went wrong while updating password. Please try again later.</div>');
                error_msg();
                $('.loading-container').addClass('hide');
            }
        });
    });
//Manage Resource---------------------------------------------------------------
    //Files---------------------------------------------------------------------
    $('#files-table').dataTable({
        "aoColumnDefs": [{
                "bSortable": false,
                "aTargets": [0, 4]}],
    });
    $('#upload-file-popup #upload-file-form').validate({
        rules: {
            filename: 'required',
            userfile: 'required',
        },
        submitHandler: function(form) {
            $('.loading-container').removeClass('hide');
            $.ajaxFileUpload({
                url: $url + 'file/upload',
                secureuri: false,
                fileElementId: 'userfile',
                dataType: 'json',
                data: {'filename': $('#filename').val(), 'type': $('.select-file-type option:selected').val()},
                success: function(data, status) {
                    if (data.status !== 'error') {
                        $('#upload-file-popup').modal('hide');
                        refresh_files_table();
                        $('.alert-success').remove();
                        $('.alert-danger').remove();
                        $('.resource-container').prepend('<div class="alert alert-success margin-top">' + data.msg + '</div>');
                        success_msg();
                        $('.loading-container').addClass('hide');
                    } else {
                        $('.alert-danger').remove();
                        $('#upload-file-popup .modal-body').prepend('<div class="alert alert-danger">' + data.msg + '</div>');
                        error_msg();
                        $('.loading-container').addClass('hide');
                    }
                },
                error: function() {
                    $('#upload-file-popup').modal('hide');
                    $('.alert-success').remove();
                    $('.alert-danger').remove();
                    $('.resource-container').prepend('<div class="alert alert-success margin-top">Something went wrong while uploading file/s. Please try again later.</div>');
                    error_msg();
                    $('.loading-container').addClass('hide');
                }
            });
            return false;
        }
    });
    $('#upload-file-popup').on('hidden.bs.modal', function() {
        $('#upload-file-popup .alert-danger').remove();
        $('#upload-file-popup input.error').removeClass('error');
        $('#upload-file-popup label.error').remove();
        $('#upload-file-popup #filename').val('');
        $('#upload-file-popup #userfile').val('');
    });
    $('.files-list .check-all-files').click(function() {
        if ($(this).is(':checked')) {
            if ($('.files-list tr td input[class=item-file-checkbox]').hasClass('item-file-checkbox')) {
                $('.btn-delete-files').removeClass('hide-element');
                $('.files-list tr td input[class=item-file-checkbox]').prop('checked', true);
            } else {
                $('.btn-delete-files').addClass('hide-element');
                $(this).prop('checked', false);
            }
        } else {
            $('.btn-delete-files').addClass('hide-element');
            $('.files-list tr td input[class=item-file-checkbox]').prop('checked', false);
        }
    });
    $('.files-list').on('click', '.item-file-checkbox', function() {
        var $checked_item = $('.files-list .item-file-checkbox:checked').size();
        if ($(this).is(':checked')) {
            $('.btn-delete-files').removeClass('hide-element');
        } else {
            if ($checked_item > 0) {
                $('.btn-delete-files').removeClass('hide-element');
            } else {
                $('.btn-delete-files').addClass('hide-element');
                $('.files-list .check-all-files').prop('checked', false);
            }
        }
    });
    $('#delete-file-popup .btn-yes').click(function() {
        var fileId = new Array();
        $('.files-list .item-file-checkbox:checked').each(function() {
            fileId.push($(this).val());
        });
        var file = {'file_id': fileId};
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'files/delete',
            type: 'post',
            data: file,
            dataType: 'json',
            success: function(data) {
                $('#delete-file-popup').modal('hide');
                $('.files-list .check-all-files').prop('checked', false);
                $('.btn-delete-files').addClass('hide-element');
                $('.alert-danger').remove();
                $('.alert-success').remove();
                $('.resource-container').prepend('<div class="alert alert-success margin-top">' + data.msg + '</div>');
                var $table = $('#files-table').dataTable();
                $('.files-list .item-file-checkbox:checked').each(function() {
                    $table.fnDeleteRow($table.fnGetPosition($(this).closest('tr')[0]));
                });
                refresh_files_table();
                success_msg();
                $('.loading-container').addClass('hide');
            },
            error: function() {
                $('#delete-file-popup').modal('hide');
                $('.alert-danger').remove();
                $('.alert-success').remove();
                $('.resource-container').prepend('<div class="alert alert-danger margin-top">Something went wrong while deleting file/s. Please try again later.</div>');
                error_msg();
                $('.loading-container').addClass('hide');
            }
        });
    });
    //Venues--------------------------------------------------------------------
    $('#venues-table').dataTable({
        "aoColumnDefs": [{
                "bSortable": false,
                "aTargets": [0]}],
    });
    $('#new-venue-popup #venue-form').validate({
        rules: {
            venue_name: 'required',
            venue_address: 'required',
        },
        submitHandler: function(form) {
            var venue = {
                'venue_name': $('#new-venue-popup .venue-name').val(),
                'venue_address': $('#new-venue-popup .venue-address').val(),
                'action': $('#new-venue-popup #n-venue-action').val(),
            };
            save_venue(venue, $('#new-venue-popup').attr('id'));
            return false;
        }
    });
    $('#new-venue-popup').on('hidden.bs.modal', function() {
        $('#new-venue-popup .alert-danger').remove();
        $('#new-venue-popup input.error').removeClass('error');
        $('#new-venue-popup label.error').remove();
        $('#new-venue-popup #n-venue-name').val('');
        $('#new-venue-popup #n-venue-address').val('');
    });
    $('.venues-list .check-all-venues').click(function() {
        if ($(this).is(':checked')) {
            if ($('.venues-list tr td input[type=checkbox]').hasClass('item-venue-checkbox')) {
                $('.btn-delete-venues').removeClass('hide-element');
                $('.venues-list tr td input[type=checkbox]').prop('checked', true);
            } else {
                $('.btn-delete-venues').addClass('hide-element');
                $(this).prop('checked', false);
            }
        } else {
            $('.btn-delete-venues').addClass('hide-element');
            $('.venues-list tr td input[class=item-venue-checkbox]').prop('checked', false);
        }
    });
    $('.venues-list').on('click', '.item-venue-checkbox', function() {
        var $checkedItem = $('.venues-list .item-venue-checkbox:checked').size();
        if ($(this).is(':checked')) {
            $('.btn-delete-venues').removeClass('hide-element');
        } else {
            if ($checkedItem > 0) {
                $('.btn-delete-venues').removeClass('hide-element');
            } else {
                $('.btn-delete-venues').addClass('hide-element');
                $('.venues-list .check-all-venues').prop('checked', false);
            }
        }
    });
    $('#delete-venue-popup .btn-yes').click(function() {
        var venueId = new Array();
        $('.venues-list .item-venue-checkbox:checked').each(function() {
            venueId.push($(this).val());
        });
        var venue = {'venue_id': venueId};
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'venues/delete',
            type: 'post',
            data: venue,
            dataType: 'json',
            success: function(data) {
                $('#delete-venue-popup').modal('hide');
                $('.alert-success').remove();
                $('.alert-danger').remove();
                $('.resource-container').prepend('<div class="alert alert-success margin-top">' + data.msg + '</div>');
                var $table = $('#venues-table').dataTable();
                $('.venues-list .item-venue-checkbox:checked').each(function() {
                    $table.fnDeleteRow($table.fnGetPosition($(this).closest('tr')[0]));
                });
                refresh_venues_table();
                success_msg();
                $('.venues-list .check-all-venues').prop('checked', false);
                $('.venues-list .item-venue-checkbox:checked').parent().parent().remove();
                $('.btn-delete-venues').addClass('hide-element');
                $('.loading-container').addClass('hide');
            },
            error: function() {
                $('#delete-venue-popup').modal('hide');
                $('.alert-success').remove();
                $('.alert-danger').remove();
                $('.resource-container').prepend('<div class="alert alert-success margin-top">Something went wrong while deleting venue/s. Please try again later.</div>');
                error_msg();
                $('.loading-container').addClass('hide');
            }
        });
    });
    //Event Types---------------------------------------------------------------
    $('#event-types-table').dataTable({
        "aoColumnDefs": [{
                "bSortable": false,
                "aTargets": [0]}],
    });
    $('.btn-new-event-type').click(function() {
        if ($('#event-type-name').val() !== '') {
            $('.loading-container').addClass('hide');
            $.ajax({
                url: $url + 'event-type/save',
                type: 'post',
                data: {'event_type_name': $('#event-type-name').val()},
                dataType: 'json',
                success: function(data) {
                    if (data.status === 'success') {
                        $('#event-type-name').val('');
                        $('.event-type-filter').find('.required-error').remove();
                        $('.alert-success').remove();
                        $('.alert-danger').remove();
                        $('.resource-container').prepend('<div class="alert alert-success margin-top">' + data.msg + '</div>');
                        success_msg();
                        refresh_event_types_table();
                        $('.loading-container').addClass('hide');
                    } else {
                        $('.alert-success').remove();
                        $('.alert-danger').remove();
                        $('.resource-container').prepend('<div class="alert alert-danger margin-top">' + data.msg + '</div>');
                        error_msg();
                        $('.loading-container').addClass('hide');
                    }
                },
                error: function() {
                    $('.alert-success').remove();
                    $('.alert-danger').remove();
                    $('.resource-container').prepend('<div class="alert alert-danger margin-top">Something went wrong while saving the event type. Please try again later.</div>');
                    error_msg();
                    $('.loading-container').addClass('hide');
                }
            });
        } else {
            if (!$('.new-event-type-form label').hasClass('required-error')) {
                $('.new-event-type-form .required').parent().after('<label class="required-error new-event-type-error">This field is required.</label>');
            }
        }
    });
    $('.event-types-list .check-all-event-types').click(function() {
        if ($(this).is(':checked')) {
            if ($('.event-types-list tr td input[type=checkbox]').hasClass('item-event-type-checkbox')) {
                $('.btn-delete-event-types').removeClass('hide-element');
                $('.event-types-list tr td input[type=checkbox]').prop('checked', true);
            } else {
                $('.btn-delete-event-types').addClass('hide-element');
                $(this).prop('checked', false);
            }
        } else {
            $('.btn-delete-event-types').addClass('hide-element');
            $('.event-types-list tr td input[type=checkbox]').prop('checked', false);
        }
    });
    $('.event-types-list').on('click', '.item-event-type-checkbox', function() {
        var $checked_item = $('.event-types-list .item-event-type-checkbox:checked').size();
        if ($(this).is(':checked')) {
            $('.btn-delete-event-types').removeClass('hide-element');
        } else {
            if ($checked_item > 0) {
                $('.btn-delete-event-types').removeClass('hide-element');
            } else {
                $('.btn-delete-event-types').addClass('hide-element');
                $('.event-types-list .check-all-event-types').prop('checked', false);
            }
        }
    });
    $('#delete-event-type-popup .btn-yes').click(function() {
        var typeId = new Array();
        $('.event-types-list .item-event-type-checkbox:checked').each(function() {
            typeId.push($(this).val());
        });
        var type = {'type_id': typeId};
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'event-types/delete',
            type: 'post',
            data: type,
            dataType: 'json',
            success: function(data) {
                if (data.status == 'success') {
                    $('#delete-event-type-popup').modal('hide');
                    $('.alert-danger').remove();
                    $('.alert-success').remove();
                    $('.resource-container').prepend('<div class="alert alert-success margin-top">' + data.msg + '</div>');
                    var $table = $('#event-types-table').dataTable();
                    $('.event-types-list .item-event-type-checkbox:checked').each(function() {
                        $table.fnDeleteRow($table.fnGetPosition($(this).closest('tr')[0]));
                    });
                    refresh_event_types_table();
                    success_msg();
                    $('.event-types-list .check-all-event-types').prop('checked', false);
                    $('.event-types-list .item-event-type-checkbox:checked').parent().parent().remove();
                    $('.btn-delete-event-types').addClass('hide-element');
                    $('.loading-container').addClass('hide');
                } else if (data.status == 'error') {
                    $('#delete-event-type-popup').modal('hide');
                    $('.alert-danger').remove();
                    $('.alert-success').remove();
                    $('.resource-container').prepend('<div class="alert alert-danger margin-top">' + data.msg + '</div>');
                    error_msg();
                    $('.loading-container').addClass('hide');
                }
            },
            error: function() {
                $('#delete-event-type-popup').modal('hide');
                $('.alert-danger').remove();
                $('.alert-success').remove();
                $('.resource-container').prepend('<div class="alert alert-danger margin-top">Something went wrong while deleting event type. Please try again later.</div>');
                error_msg();
                $('.loading-container').addClass('hide');
            }
        });
    });
    //General Checklist---------------------------------------------------------
    $('.general-checklist-nav a[data-toggle="tab"]').on('shown.bs.tab', function() {
        $('#general-checklist #accordion').empty();
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'general-checklist/get',
            type: 'post',
            dataType: 'json',
            success: function(data) {
                if (data != false) {
                    $.each(data, function(key, value) {
                        $('#general-checklist #accordion').prepend('<div class="panel panel-default">' +
                                '<div class="panel-heading"><h4 class="panel-title">' +
                                '<a data-toggle="collapse" data-parent="#accordion" href="#' + value.category_name.replace(/ /g, '-').toLowerCase() + '">' +
                                value.category_name + '</a><a href="#delete-cat-popup" data-catid="' + value.category_id +
                                '" class="btn btn-primary btn-delete-cat btn-xs pull-right"' +
                                'data-toggle="modal" title="Delete Category"><span class="glyphicon glyphicon-remove"></span></a>' +
                                '</h4></div><div id="' + value.category_name.replace(/ /g, '-').toLowerCase() + '" class="panel-collapse collapse"><div class="panel-body">' +
                                '<div class="list-group"><div class="form-inline new-sub-category-form"><div class="input-group"><input type="text" data-catid="' + value.category_id +
                                '" class="form-control g-c-sub-cat-name" name="sub_cat_name" placeholder="New Sub Category...">' +
                                '<span class="input-group-btn"><button class="btn btn-default btn-new-g-c-sub-cat" type="button"><span class="glyphicon glyphicon-plus"></span></button>' +
                                '</span></div></div><div class="sub-cat-list"></div></div></div></div></div>');
                    });
                    $('.loading-container').addClass('hide');
                } else {
                    $('#general-checklist').find('.alert-info').remove();
                    $('#general-checklist .panel-group').before('<div class="alert alert-info general-checklist-empty">Your general checklist is currently empty.</div>');
                    $('.loading-container').addClass('hide');
                }
            },
            error: function(xhr, status) {
                $('.loading-container').addClass('hide');
            }
        });
    });
    $('#general-checklist').on('click', 'a[data-toggle="collapse"]', function() {
        var $catId = $(this).siblings().attr('data-catid');
        var $target = $(this).parent().parent().siblings().children().children().children('.sub-cat-list');
        if ($(this).parent().parent().siblings().hasClass('collapse')) {
            if ($target.children().length === 0) {
                $('.loading-container').removeClass('hide');
                $.ajax({
                    url: $url + 'general-checklist/sub-cat/' + $catId,
                    type: 'post',
                    dataType: 'json',
                    success: function(sub_cat) {
                        if (sub_cat !== false) {
                            $.each(sub_cat, function(key, value) {
                                $target.append('<a href="#delete-sub-cat-popup" class="list-group-item sub-cat-item" data-toggle="modal" data-catid="' + value.category_id +
                                        '" data-subcatid="' + value.checklist_id + '">' + value.list_description +
                                        '<span class="glyphicon glyphicon-remove pull-right"></span></a>');
                            });
                            $('.loading-container').addClass('hide');
                        } else {
                            if ($target.find('.empty-msg').length === 0) {
                                $target.append('<a href="#" class="list-group-item empty-msg">Oops! No sub category found.</a>');
                            }
                            $('.loading-container').addClass('hide');
                        }
                    },
                    error: function(xhr, status) {
                        $('.loading-container').addClass('hide');
                    }
                });
            }
        }
    });
    $('.btn-new-g-c-category').click(function() {
        if ($('#g-c-category-name').val() !== '') {
            $('.loading-container').removeClass('hide');
            $.ajax({
                url: $url + 'general-checklist/save-new-cat',
                type: 'post',
                dataType: 'json',
                data: {'category': $('#g-c-category-name').val()},
                success: function(data) {
                    if (data.status === 'success') {
                        $('#general-checklist').find('.general-checklist-empty').remove();
                        $('#general-checklist #accordion').prepend('<div class="panel panel-default">' +
                                '<div class="panel-heading"><h4 class="panel-title">' +
                                '<a data-toggle="collapse" data-parent="#accordion" href="#' + data.cat.category_name.replace(/ /g, '-').toLowerCase() + '">' +
                                data.cat.category_name + '</a><a href="#delete-cat-popup" data-catid="' + data.cat.category_id +
                                '" class="btn btn-primary btn-delete-cat btn-xs pull-right"' +
                                'data-toggle="modal" title="Delete Category"><span class="glyphicon glyphicon-remove"></span></a>' +
                                '</h4></div><div id="' + data.cat.category_name.replace(/ /g, '-').toLowerCase() + '" data-catid="' + data.cat.category_id + '" class="panel-collapse collapse"><div class="panel-body">' +
                                '<div class="list-group"><div class="form-inline new-sub-category-form"><div class="input-group"><input type="text" data-catid="' + data.cat.category_id + '" class="form-control g-c-sub-cat-name" name="sub_cat_name" placeholder="New Sub Category...">' +
                                '<span class="input-group-btn"><button class="btn btn-default btn-new-g-c-sub-cat" type="button"><span class="glyphicon glyphicon-plus"></span></button>' +
                                '</span></div></div><div class="sub-cat-list"></div></div></div></div></div>');
                        $('#g-c-category-name').val('');
                        $('.new-category-form').find('.required-error').remove();
                        $('.alert-danger').remove();
                        $('.alert-success').remove();
                        $('#general-checklist').prepend('<div class="alert alert-success">' + data.msg + '</div>');
                        success_msg();
                        $('.loading-container').addClass('hide');
                    } else {
                        $('.alert-danger').remove();
                        $('.alert-success').remove();
                        $('#general-checklist').prepend('<div class="alert alert-danger">' + data.msg + '</div>');
                        error_msg();
                        $('.loading-container').addClass('hide');
                    }
                },
                error: function() {
                    $('.alert-danger').remove();
                    $('.alert-success').remove();
                    $('#general-checklist').prepend('<div class="alert alert-danger">Something went wrong while saving the category. Please try again later.</div>');
                    error_msg();
                    $('.loading-container').addClass('hide');
                }
            });
        } else {
            if (!$('.new-category-form p').hasClass('required-error')) {
                $('.new-category-form').append('<p class="required-error">This field is required.</p>');
            }
        }
    });
    $('#general-checklist #accordion').on('click', '.btn-delete-cat', function() {
        var $catId = $(this).attr('data-catid');
        $('#delete-cat-popup .btn-yes').attr('data-catid', $catId);
        $(this).addClass('cat-to-be-deleted');
    });
    $('#delete-cat-popup .btn-yes').click(function() {
        var $catId = $(this).attr('data-catid');
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'general-checklist/delete-cat/' + $catId,
            type: 'post',
            dataType: 'json',
            success: function(data) {
                if (data.status == 'success') {
                    $('#general-checklist #accordion').find('.cat-to-be-deleted').parent().parent().parent().remove();
                    $('#delete-cat-popup').modal('hide');
                    $('.alert-danger').remove();
                    $('.alert-success').remove();
                    $('#general-checklist').prepend('<div class="alert alert-success">' + data.msg + '</div>');
                    success_msg();
                    $('.loading-container').addClass('hide');
                } else {
                    $('.alert-danger').remove();
                    $('.alert-success').remove();
                    $('#general-checklist').prepend('<div class="alert alert-danger">' + data.msg + '</div>');
                    error_msg();
                    $('.loading-container').addClass('hide');
                }
            },
            error: function() {
                $('.alert-danger').remove();
                $('.alert-success').remove();
                $('#general-checklist').prepend('<div class="alert alert-danger">Something went wrong while deleting the category. Please try again later.</div>');
                error_msg();
                $('.loading-container').addClass('hide');
            }
        });
    });
    $('#delete-cat-popup').on('hide.bs.modal', function() {
        $('#general-checklist #accordion').find('.cat-to-be-deleted').removeClass('cat-to-be-deleted');
    });
    $('#general-checklist #accordion').on('click', '.btn-new-g-c-sub-cat', function() {
        var $current = $(this).parent().siblings();
        var $target = $(this).parent().parent().parent().siblings('.sub-cat-list');
        var sub_cat = {
            'sub_category': $(this).parent().siblings().val(),
            'cat_id': $(this).parent().siblings().attr('data-catid'),
        };
        if ($(this).parent().siblings().val() !== '') {
            $('.loading-container').removeClass('hide');
            $.ajax({
                url: $url + 'general-checklist/save-new-sub-cat',
                type: 'post',
                dataType: 'json',
                data: sub_cat,
                success: function(data) {
                    if (data.status === 'success') {
                        $target.prepend('<a href="#delete-sub-cat-popup" class="list-group-item sub-cat-item" data-toggle="modal" data-subcatid="' + data.sub_cat.checklist_id +
                                '">' + data.sub_cat.list_description + '<span class="glyphicon glyphicon-remove pull-right"></span></a>');
                        $current.val('');
                        $current.parent().parent().siblings().find('.empty-msg').remove();
                        $('.new-sub-category-form').find('.required-error').remove();
                        $('.alert-danger').remove();
                        $('.alert-success').remove();
                        $current.parent().before('<div class="alert alert-success">' + data.msg + '</div>');
                        success_msg();
                        $('.loading-container').addClass('hide');
                    } else {
                        $('.alert-danger').remove();
                        $('.alert-success').remove();
                        $current.parent().before('<div class="alert alert-danger">' + data.msg + '</div>');
                        error_msg();
                        $('.loading-container').addClass('hide');
                    }
                },
                error: function() {
                    $('.alert-danger').remove();
                    $('.alert-success').remove();
                    $current.parent().before('<div class="alert alert-danger">Something went wrong while saving the category. Please try again later.</div>');
                    error_msg();
                    $('.loading-container').addClass('hide');
                }
            });
        } else {
            if (!$('.new-sub-category-form p').hasClass('required-error')) {
                $('.new-sub-category-form').append('<p class="required-error">This field is required.</p>');
            }
        }
    });
    $('#general-checklist #accordion').on('click', '.sub-cat-item', function() {
        var $subCatId = $(this).attr('data-subcatid');
        $('#delete-sub-cat-popup .btn-yes').attr('data-subcatid', $subCatId);
        $(this).addClass('sub-cat-to-be-deleted');
    });
    $('#delete-sub-cat-popup .btn-yes').click(function() {
        var $subCatId = $(this).attr('data-subcatid');
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'general-checklist/delete-sub-cat/' + $subCatId,
            type: 'post',
            dataType: 'json',
            success: function(data) {
                if (data.status == 'success') {
                    $('.alert-danger').remove();
                    $('.alert-success').remove();
                    $('.sub-cat-to-be-deleted').parent().parent().before('<div class="alert alert-success">' + data.msg + '</div>');
                    success_msg();
                    $('#general-checklist #accordion .sub-cat-list').find('.sub-cat-to-be-deleted').remove();
                    $('#delete-sub-cat-popup').modal('hide');
                    $('.loading-container').addClass('hide');
                } else {
                    $('.alert-danger').remove();
                    $('.alert-success').remove();
                    $('.sub-cat-to-be-deleted').parent().parent().before('<div class="alert alert-danger">' + data.msg + '</div>');
                    error_msg();
                    $('#general-checklist #accordion .sub-cat-list').find('.sub-cat-to-be-deleted').remove();
                    $('#delete-sub-cat-popup').modal('hide');
                    $('.loading-container').addClass('hide');
                }
            },
            error: function() {
                $('.alert-danger').remove();
                $('.alert-success').remove();
                $('.sub-cat-to-be-deleted').parent().parent().before('<div class="alert alert-danger">Something went wrong while deleting the sub category. Please try again later.</div>');
                error_msg();
                $('#general-checklist #accordion .sub-cat-list').find('.sub-cat-to-be-deleted').remove();
                $('#delete-sub-cat-popup').modal('hide');
                $('.loading-container').addClass('hide');
            }
        });
    });
    $('#delete-sub-cat-popup').on('hide.bs.modal', function() {
        $('#general-checklist #accordion .sub-cat-list').find('.sub-cat-to-be-deleted').removeClass('sub-cat-to-be-deleted');
    });
//Messages----------------------------------------------------------------------
    $('#compose-msg-popup .btn-browse-file').click(function() {
        $('#compose-msg-popup .userfile').click();
    });
    $('#compose-msg-popup .userfile').change(function() {
        $('#compose-msg-popup .file-upload').val($(this).val());
    });
    //Inbox---------------------------------------------------------------------
    $('#inbox-table').dataTable({
        "aoColumnDefs": [{
                "bSortable": false,
                "aTargets": [0],
            }]
    });
    // view message
    $('#view-inbox-msg-popup .reply-container .btn-browse-file').click(function() {
        $('#view-inbox-msg-popup .reply-container .userfile').click();
    });
    $('#view-inbox-msg-popup .reply-container .userfile').change(function() {
        $('#view-inbox-msg-popup .reply-container .file-upload').val($(this).val());
    });
    $('#view-inbox-msg-popup .forward-container .btn-browse-file').click(function() {
        $('#view-inbox-msg-popup .forward-container .userfile').click();
    });
    $('#view-inbox-msg-popup .forward-container .userfile').change(function() {
        $('#view-inbox-msg-popup .forward-container .file-upload').val($(this).val());
    });
    $('.inbox-list').on('click', '.btn-view-inbox-msg', function() {
        $('#view-inbox-msg-popup .msg-id').val($(this).parent().siblings().children().val());
    });
    $('#view-inbox-msg-popup').on('show.bs.modal', function() {
        var $msgId = $('#view-inbox-msg-popup .msg-id').val();
        get_inbox_msg($msgId);
    });
    $('#view-inbox-msg-popup .select-view-msg').click(function() {
        $('#view-inbox-msg').text('View Message');
        $(this).addClass('btn-primary').removeClass('btn-default').attr('disabled', true);
        $('#view-inbox-msg-popup .select-reply-msg').addClass('btn-default').removeClass('btn-primary').attr('disabled', false);
        $('#view-inbox-msg-popup .select-forward-msg').addClass('btn-default').removeClass('btn-primary').attr('disabled', false);
        $('#view-inbox-msg-popup .view-container').removeClass('hide-element');
        $('#view-inbox-msg-popup .reply-container').addClass('hide-element');
        $('#view-inbox-msg-popup .forward-container').addClass('hide-element');
        $('#view-inbox-msg-popup .btn-save').addClass('hide-element');
        $('#view-inbox-msg-popup .btn-send').addClass('hide-element');
    });
    $('#view-inbox-msg-popup .select-reply-msg').click(function() {
        $('#view-inbox-msg').text('Reply Message');
        $('#view-inbox-msg-popup .select-view-msg').addClass('btn-default').removeClass('btn-primary').attr('disabled', false);
        $(this).addClass('btn-primary').removeClass('btn-default').attr('disabled', true);
        $('#view-inbox-msg-popup .select-forward-msg').addClass('btn-default').removeClass('btn-primary').attr('disabled', false);
        $('#view-inbox-msg-popup .view-container').addClass('hide-element');
        $('#view-inbox-msg-popup .reply-container').removeClass('hide-element');
        $('#view-inbox-msg-popup .forward-container').addClass('hide-element');
        $('#view-inbox-msg-popup .btn-save').removeClass('hide-element');
        $('#view-inbox-msg-popup .btn-send').removeClass('hide-element');
    });
    $('#view-inbox-msg-popup .select-forward-msg').click(function() {
        $('#view-inbox-msg').text('Forward Message');
        $('#view-inbox-msg-popup .select-view-msg').addClass('btn-default').removeClass('btn-primary').attr('disabled', false);
        $('#view-inbox-msg-popup .select-reply-msg').addClass('btn-default').removeClass('btn-primary').attr('disabled', false);
        $(this).addClass('btn-primary').removeClass('btn-default').attr('disabled', true);
        $('#view-inbox-msg-popup .view-container').addClass('hide-element');
        $('#view-inbox-msg-popup .reply-container').addClass('hide-element');
        $('#view-inbox-msg-popup .forward-container').removeClass('hide-element');
        $('#view-inbox-msg-popup .btn-save').removeClass('hide-element');
        $('#view-inbox-msg-popup .btn-send').removeClass('hide-element');
    });
    $('#view-inbox-msg-popup .btn-send').click(function() {
        var msgInfo = {};
        var fileId = '';
        if ($('#view-inbox-msg-popup .select-reply-msg').attr('disabled') == 'disabled') {
            msgInfo = {
                'recipient': $('#view-inbox-msg-popup .reply-container .msg-recipient').attr('data-recipientid'),
                'subject': $('#view-inbox-msg-popup .reply-container .msg-subject').val(),
                'msg_body': $('#view-inbox-msg-popup .reply-container .msg-body').val(),
                'userfile': $('#view-inbox-msg-popup .reply-container #i-r-userfile').val(),
                'file_id': $('#view-inbox-msg-popup .reply-container #i-r-userfile').attr('id'),
                'date_time': date_time(),
                'action': 0,
            };
            fileId = $('#view-inbox-msg-popup .reply-container #i-r-userfile').attr('id');
        } else if ($('#view-inbox-msg-popup .select-forward-msg').attr('disabled') == 'disabled') {
            msgInfo = {
                'recipient': $('#view-inbox-msg-popup .forward-container .msg-recipient option:selected').val(),
                'subject': $('#view-inbox-msg-popup .forward-container .msg-subject').val(),
                'msg_body': $('#view-inbox-msg-popup .forward-container .msg-body').val(),
                'userfile': $('#view-inbox-msg-popup .forward-container #i-f-userfile').val(),
                'file_id': $('#view-inbox-msg-popup .forward-container #i-f-userfile').attr('id'),
                'date_time': date_time(),
                'action': 0,
            };
            fileId = $('#view-inbox-msg-popup .forward-container #i-f-userfile').attr('id');
        }
        if (msgInfo.recipient != 'Recipient' && msgInfo.subject != '') {
            $('#view-inbox-msg-popup .required-error').remove();
            if (msgInfo.userfile == '') {
                send_default_msg($('#view-inbox-msg-popup').attr('id'), msgInfo);
            } else {
                send_attachment_msg($('#view-inbox-msg-popup').attr('id'), msgInfo, fileId);
            }
        } else {
            if (!$('#view-inbox-msg-popup p').hasClass('required-error')) {
                $('#view-inbox-msg-popup .required').parent().append('<p class="required-error">This field is required.</p>');
                $('#view-inbox-msg-popup .required-info').after('<p class="required-error">This field is required.</p>');
            }
        }
    });
    // delete inbox messages
    $('.inbox-list .check-all-inbox').click(function() {
        if ($(this).is(':checked')) {
            if ($('.inbox-list tr td input[type=checkbox]').hasClass('item-inbox-checkbox')) {
                $('.btn-delete-inbox').removeClass('hide-element');
                $('.inbox-list tr td input[type=checkbox]').prop('checked', true);
            } else {
                $('.btn-delete-inbox').addClass('hide-element');
                $(this).prop('checked', false);
            }
        } else {
            $('.btn-delete-inbox').addClass('hide-element');
            $('.inbox-list tr td input[type=checkbox]').prop('checked', false);
        }
    });
    $('.inbox-list').on('click', '.item-inbox-checkbox', function() {
        var $checked_item = $('.inbox-list .item-inbox-checkbox:checked').size();
        if ($(this).is(':checked')) {
            $('.btn-delete-inbox').removeClass('hide-element');
        } else {
            if ($checked_item > 0) {
                $('.btn-delete-inbox').removeClass('hide-element');
            } else {
                $('.btn-delete-inbox').addClass('hide-element');
                $('.inbox-list .check-all-inbox').prop('checked', false);
            }
        }
    });
    $('#delete-inbox-popup .btn-yes').click(function() {
        var msgId = new Array();
        $('.inbox-list .item-inbox-checkbox:checked').each(function() {
            msgId.push($(this).val());
        });
        var type = {'msg_id': msgId};
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'messages/inbox/delete',
            type: 'post',
            data: type,
            dataType: 'json',
            success: function(data) {
                $('#delete-inbox-popup').modal('hide');
                $('.alert-success').remove();
                $('.alert-danger').remove();
                $('.messages-container').prepend('<div class="alert alert-success margin-top">' + data.msg + '</div>');
                var $table = $('#inbox-table').dataTable();
                $('.inbox-list .item-inbox-checkbox:checked').each(function() {
                    $table.fnDeleteRow($table.fnGetPosition($(this).closest('tr')[0]));
                });
                refresh_inbox_table();
                success_msg();
                $('.inbox-list .check-all-inbox').prop('checked', false);
                $('.inbox-list .item-inbox-checkbox:checked').parent().parent().remove();
                $('.btn-delete-inbox').addClass('hide-element');
                $('.loading-container').addClass('hide');
            },
            error: function() {
                $('#delete-inbox-popup').modal('hide');
                $('.alert-danger').remove();
                $('.alert-success').remove();
                $('.messages-container').prepend('<div class="alert alert-danger margin-top">Something went wrong while deleting messages on your inbox. Please try again later.</div>');
                error_msg();
                $('.loading-container').addClass('hide');
            }
        });
    });

    $('#view-inbox-msg-popup .select-delete-msg').click(function() {
        var msgId = new Array();
        msgId.push($('#view-inbox-msg-popup .msg-id').val());
        var type = {'msg_id': msgId};
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'messages/inbox/delete',
            type: 'post',
            data: type,
            dataType: 'json',
            success: function(data) {
                $('#view-inbox-msg-popup').modal('hide');
                $('.alert-danger').remove();
                $('.alert-success').remove();
                $('.messages-container').prepend('<div class="alert alert-success margin-top">' + data.msg + '</div>');
                refresh_inbox_table();
                success_msg();
                $('.loading-container').addClass('hide');
            },
            error: function() {
                $('#view-inbox-msg-popup').modal('hide');
                $('.alert-danger').remove();
                $('.alert-success').remove();
                $('.messages-container').prepend('<div class="alert alert-danger margin-top">Something went wrong while deleting messages on your inbox. Please try again later.</div>');
                error_msg();
                $('.loading-container').addClass('hide');
            }
        });
    });
    //Sentbox-------------------------------------------------------------------
    $('#sentbox-table').dataTable({
        "aoColumnDefs": [{
                "bSortable": false,
                "aTargets": [0],
            }]
    });
    $('#view-sentbox-msg-popup .forward-container .btn-browse-file').click(function() {
        $('#view-sentbox-msg-popup .forward-container .userfile').click();
    });
    $('#view-sentbox-msg-popup .forward-container .userfile').change(function() {
        $('#view-sentbox-msg-popup .forward-container .file-upload').val($(this).val());
    });
    $('.sentbox-list').on('click', '.btn-view-sentbox-msg', function() {
        $('#view-sentbox-msg-popup .msg-id').val($(this).parent().siblings().children().val());
    });
    $('#view-sentbox-msg-popup').on('show.bs.modal', function() {
        var $msgId = $('#view-sentbox-msg-popup .msg-id').val();
        get_sentbox_msg($msgId);
    });
    $('#view-sentbox-msg-popup .select-view-msg').click(function() {
        $('#view-sentbox-msg').text('View Message');
        $(this).addClass('btn-primary').removeClass('btn-default').attr('disabled', true);
        $('#view-sentbox-msg-popup .select-reply-msg').addClass('btn-default').removeClass('btn-primary').attr('disabled', false);
        $('#view-sentbox-msg-popup .select-forward-msg').addClass('btn-default').removeClass('btn-primary').attr('disabled', false);
        $('#view-sentbox-msg-popup .view-container').removeClass('hide-element');
        $('#view-sentbox-msg-popup .reply-container').addClass('hide-element');
        $('#view-sentbox-msg-popup .forward-container').addClass('hide-element');
        $('#view-sentbox-msg-popup .btn-save').addClass('hide-element');
        $('#view-sentbox-msg-popup .btn-send').addClass('hide-element');
    });
    $('#view-sentbox-msg-popup .select-forward-msg').click(function() {
        $('#view-sentbox-msg').text('Forward Message');
        $('#view-sentbox-msg-popup .select-view-msg').addClass('btn-default').removeClass('btn-primary').attr('disabled', false);
        $('#view-sentbox-msg-popup .select-reply-msg').addClass('btn-default').removeClass('btn-primary').attr('disabled', false);
        $(this).addClass('btn-primary').removeClass('btn-default').attr('disabled', true);
        $('#view-sentbox-msg-popup .view-container').addClass('hide-element');
        $('#view-sentbox-msg-popup .reply-container').addClass('hide-element');
        $('#view-sentbox-msg-popup .forward-container').removeClass('hide-element');
        $('#view-sentbox-msg-popup .btn-save').removeClass('hide-element');
        $('#view-sentbox-msg-popup .btn-send').removeClass('hide-element');
    });
    $('#view-sentbox-msg-popup .btn-send').click(function() {
        var msgInfo = {};
        var fileId = '';
        if ($('#view-sentbox-msg-popup .select-forward-msg').attr('disabled') == 'disabled') {
            msgInfo = {
                'recipient': $('#view-sentbox-msg-popup .forward-container .msg-recipient option:selected').val(),
                'subject': $('#view-sentbox-msg-popup .forward-container .msg-subject').val(),
                'msg_body': $('#view-sentbox-msg-popup .forward-container .msg-body').val(),
                'userfile': $('#view-sentbox-msg-popup .forward-container #s-f-userfile').val(),
                'file_id': $('#view-sentbox-msg-popup .forward-container #s-f-userfile').attr('id'),
                'date_time': date_time(),
            };
            fileId = $('#view-sentbox-msg-popup .forward-container #s-f-userfile').attr('id');
        }
        if (msgInfo.recipient != 'Recipient' && msgInfo.subject != '') {
            $('#view-sentbox-msg-popup .required-error').remove();
            if (msgInfo.userfile == '') {
                send_default_msg($('#view-sentbox-msg-popup').attr('id'), msgInfo);
            } else {
                send_attachment_msg($('#view-sentbox-msg-popup').attr('id'), msgInfo, fileId);
            }
        } else {
            if (!$('#view-sentbox-msg-popup p').hasClass('required-error')) {
                $('#view-sentbox-msg-popup .required').parent().append('<p class="required-error">This field is required.</p>');
                $('#view-sentbox-msg-popup .required-info').after('<p class="required-error">This field is required.</p>');
            }
        }
    });
    // delete inbox messages
    $('.sentbox-list .check-all-sentbox').click(function() {
        if ($(this).is(':checked')) {
            if ($('.sentbox-list tr td input[type=checkbox]').hasClass('item-sentbox-checkbox')) {
                $('.btn-delete-sentbox').removeClass('hide-element');
                $('.sentbox-list tr td input[type=checkbox]').prop('checked', true);
            } else {
                $('.btn-delete-sentbox').addClass('hide-element');
                $(this).prop('checked', false);
            }
        } else {
            $('.btn-delete-sentbox').addClass('hide-element');
            $('.sentbox-list tr td input[type=checkbox]').prop('checked', false);
        }
    });
    $('.sentbox-list').on('click', '.item-sentbox-checkbox', function() {
        var $checkedItem = $('.sentbox-list .item-sentbox-checkbox:checked').size();
        if ($(this).is(':checked')) {
            $('.btn-delete-sentbox').removeClass('hide-element');
        } else {
            if ($checkedItem > 0) {
                $('.btn-delete-sentbox').removeClass('hide-element');
            } else {
                $('.btn-delete-sentbox').addClass('hide-element');
                $('.sentbox-list .check-all-sentbox').prop('checked', false);
            }
        }
    });
    $('#delete-sentbox-popup .btn-yes').click(function() {
        var msgId = new Array();
        $('.sentbox-list .item-sentbox-checkbox:checked').each(function() {
            msgId.push($(this).val());
        });
        var type = {'msg_id': msgId};
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'messages/sentbox/delete',
            type: 'post',
            data: type,
            dataType: 'json',
            success: function(data) {
                $('#delete-sentbox-popup').modal('hide');
                $('.alert-danger').remove();
                $('.alert-success').remove();
                $('.messages-container').prepend('<div class="alert alert-success margin-top">' + data.msg + '</div>');
                var $table = $('#sentbox-table').dataTable();
                $('.sentbox-list .item-sentbox-checkbox:checked').each(function() {
                    $table.fnDeleteRow($table.fnGetPosition($(this).closest('tr')[0]));
                });
                refresh_sentbox_table();
                success_msg();
                $('.sentbox-list .check-all-sentbox').prop('checked', false);
                $('.sentbox-list .item-sentbox-checkbox:checked').parent().parent().remove();
                $('.btn-delete-sentbox').addClass('hide-element');
                $('.loading-container').addClass('hide');
            },
            error: function() {
                $('#delete-sentbox-popup').modal('hide');
                $('.alert-danger').remove();
                $('.alert-success').remove();
                $('.messages-container').prepend('<div class="alert alert-danger margin-top">Something went wrong while deleting messages on your sentbox. Please try again later.</div>');
                error_msg();
                $('.loading-container').addClass('hide');
            }
        });
    });
    $('#view-sentbox-msg-popup .select-delete-msg').click(function() {
        var msgId = new Array();
        msgId.push($('#view-sentbox-msg-popup .msg-id').val());
        var type = {'msg_id': msgId};
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'messages/sentbox/delete',
            type: 'post',
            data: type,
            dataType: 'json',
            success: function(data) {
                $('#view-sentbox-msg-popup').modal('hide');
                $('.alert-danger').remove();
                $('.alert-success').remove();
                $('.messages-container').prepend('<div class="alert alert-success margin-top">' + data.msg + '</div>');
                refresh_sentbox_table();
                success_msg();
                $('.loading-container').addClass('hide');
            },
            error: function() {
                $('#view-sentbox-msg-popup').modal('hide');
                $('.alert-danger').remove();
                $('.alert-success').remove();
                $('.messages-container').prepend('<div class="alert alert-danger margin-top">Something went wrong while deleting messages on your sentbox. Please try again later.</div>');
                error_msg();
                $('.loading-container').addClass('hide');
            }
        });
    });
//    //Draft---------------------------------------------------------------------
//    $('#draft-table').dataTable({
//        "aoColumnDefs":[{
//            "bSortable":false,
//            "aTargets":[0],
//        }]
//    });
//    $('.draft-list').on('click', '.btn-view-draft-msg', function(){
//        $('#view-draft-msg-popup .msg-id').val($(this).parent().siblings().children().val());
//    });
//    $('#view-draft-msg-popup').on('show.bs.modal', function(){
//        var $msgId = $('#view-draft-msg-popup .msg-id').val();
//        get_draft_msg($msgId);
//    });
    // compose message
    $('#compose-msg-popup .btn-send').click(function() {
        var msgInfo = {
            'recipient': $('#compose-msg-popup .msg-recipient option:selected').val(),
            'subject': $('#compose-msg-popup .msg-subject').val(),
            'msg_body': $('#compose-msg-popup .msg-body').val(),
            'userfile': $('#compose-msg-popup #c-userfile').val(),
            'file_id': $('#compose-msg-popup #c-userfile').attr('id'),
            'date_time': date_time(),
            'action': 0,
        };
        if (msgInfo.recipient != 'Recipient' && msgInfo.subject != '') {
            if (msgInfo.userfile == '') {
                send_default_msg($('#compose-msg-popup').attr('id'), msgInfo);
            } else {
                send_attachment_msg($('#compose-msg-popup').attr('id'), msgInfo, $('#compose-msg-popup #c-userfile').attr('id'));
            }
        } else {
            if (!$('#compose-msg-popup p').hasClass('required-error')) {
                $('#compose-msg-popup .required').parent().append('<p class="required-error">This field is required.</p>');
                $('#compose-msg-popup .required-info').after('<p class="required-error">This field is required.</p>');
            }
        }
    });
//    $('#compose-msg-popup .btn-save').click(function(){
//        var msgInfo = {
//            'recipient':$('#compose-msg-popup .msg-recipient option:selected').val(),
//            'subject':$('#compose-msg-popup .msg-subject').val(),
//            'msg_body':$('#compose-msg-popup .msg-body').val(),
//            'userfile':$('#compose-msg-popup #c-userfile').val(),
//            'file_id':$('#compose-msg-popup #c-userfile').attr('id'),
//            'date_time': '',
//            'action': 1,
//        };
//        if(msg_info.recipient!='Recipient' && msg_info.subject!=''){
//            if(msg_info.userfile==''){
//                send_default_msg($('#compose-msg-popup').attr('id'), msg_info);
//            }else{
//                send_attachment_msg($('#compose-msg-popup').attr('id'),msg_info, $('#compose-msg-popup #c-userfile').attr('id'));
//            }
//        }else{
//            if(!$('#compose-msg-popup p').hasClass('required-error')){
//                $('#compose-msg-popup .required').parent().append('<p class="required-error">This field is required.</p>');
//                $('#compose-msg-popup .required-info').after('<p class="required-error">This field is required.</p>');
//            }
//        }
//    });
    $('#compose-msg-popup').on('hide.bs.modal', function() {
        $('#compose-msg-popup .msg-recipient').find('.default-recipient').prop('selected', true);
        $('#compose-msg-popup .msg-subject').val('');
        $('#compose-msg-popup .msg-body').val('');
        $('#compose-msg-popup .file-upload').val('');
        $('#compose-msg-popup .file-attachment').val('');
    });
//Contacts----------------------------------------------------------------------
    //Employees-----------------------------------------------------------------
    $('#employees-table').dataTable({
        "aoColumnDefs": [{
                "bSortable": false,
                "aTargets": [0]
            }],
    });
    //new employee
    $('#new-emp-popup #emp-form').validate({
        rules: {
            lname: 'required',
            fname: 'required',
            mname: 'required',
            date_emp: {
                required: true,
                date: true,
            },
            address_1: 'required',
            email_1: {
                required: true,
                email: true,
            },
            email_2: 'email',
            contact_no_1: {
                required: true,
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
            contact_no_2: {
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
            contact_no_3: {
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
        },
        groups: {
            bday: 'bday_month bday_day bday_year'
        },
        errorPlacement: function(error, element) {
            var name = element.prop('name');
            if (name === 'bday_month' || name === 'bday_day' || name === 'bday_year') {
                error.insertAfter('#new-emp-popup .bday');
            } else {
                error.insertAfter(element);
            }
        },
        submitHandler: function(form) {
            var address = new Array();
            var email = new Array();
            var contact = new Array();
            $('#new-emp-popup .address-container .address-text').each(function() {
                if ($(this).val() != '') {
                    address.push($(this).val());
                }
            });
            $('#new-emp-popup .email-container .email-text').each(function() {
                if ($(this).val() != '') {
                    email.push($(this).val());
                }
            });
            $('#new-emp-popup .contact-no-container .contact-no-text').each(function() {
                if ($(this).val() != '') {
                    contact.push($(this).val());
                }
            });
            var emp = {
                'lname': $('#new-emp-popup .lname').val(),
                'fname': $('#new-emp-popup .fname').val(),
                'mname': $('#new-emp-popup .mname').val(),
                'bday': $('#new-emp-popup .bday-year').val() + '-' + $('#new-emp-popup .bday-month').val() + '-' + $('#new-emp-popup .bday-day').val(),
                'gender': $('#new-emp-popup .gender .active input').val(),
                'date_emp': $('#new-emp-popup .date-emp').val(),
                'address': address.join(';'),
                'email': email.join(';'),
                'contact_no': contact.join(';'),
                'action': 0,
            };
            save_emp(emp, $('#new-emp-popup').attr('id'));
            return false;
        },
    });
    $('#new-emp-popup').on('hide.bs.modal', function() {
        $('#new-emp-popup .lname').val('');
        $('#new-emp-popup .fname').val('');
        $('#new-emp-popup .mname').val('');
        $('#new-emp-popup .bday-month .default-month').prop('selected', true);
        $('#new-emp-popup .bday-day .default-day').prop('selected', true);
        $('#new-emp-popup .bday-year .default-year').prop('selected', true);
        $('#new-emp-popup .date-emp').val('');
        $('#new-emp-popup .address-text').val('');
        $('#new-emp-popup .email-text').val('');
        $('#new-emp-popup .contact-no-text').val('');
        $('#new-emp-popup select.error').removeClass('error');
        $('#new-emp-popup input.error').removeClass('error');
        $('#new-emp-popup label.error').remove();
    });
    // view/edit employee
    $('#view-emp-popup').on('click', '.btn-edit-emp', function() {
        if ($(this).text() == ' Cancel Editing') {
            $(this).addClass('btn-default');
            $(this).removeClass('btn-primary');
            $(this).text('');
            $(this).append('<span class="glyphicon glyphicon-edit"></span> Edit');
            $('#view-emp').text('View Employee');
            $('#view-emp-popup .btn-update').addClass('hide');
            $('#view-emp-popup .edit-emp-container').addClass('hide');
            $('#view-emp-popup .view-emp-container').removeClass('hide');
        } else {
            $(this).removeClass('btn-default');
            $(this).addClass('btn-primary');
            $(this).text('');
            $(this).append('<span class="glyphicon glyphicon-edit"></span> Cancel Editing');
            $('#view-emp').text('Edit Employee');
            $('#view-emp-popup .btn-update').removeClass('hide');
            $('#view-emp-popup .edit-emp-container').removeClass('hide');
            $('#view-emp-popup .view-emp-container').addClass('hide');
        }
    });
    $('#employees-tab .emp-list').on('click', '.btn-view-emp', function() {
        $('#view-emp-popup #emp-id').val($(this).parent().siblings().children().val());
    });
    $('#view-emp-popup').on('show.bs.modal', function() {
        var $empId = $('#view-emp-popup #emp-id').val();
        get_emp($empId);
    });
    $('#view-emp-popup').on('hide.bs.modal', function() {
        $('#view-emp-popup .edit-emp-container .lname').val('');
        $('#view-emp-popup .edit-emp-container .fname').val('');
        $('#view-emp-popup .edit-emp-container .mname').val('');
        $('#new-emp-popup .bday-month .default-month').prop('selected', true);
        $('#new-emp-popup .bday-day .default-day').prop('selected', true);
        $('#new-emp-popup .bday-year .default-year').prop('selected', true);
        $('#view-emp-popup .edit-emp-container .date-emp').val('');
        $('#view-emp-popup .edit-emp-container .address-text').val('');
        $('#view-emp-popup .edit-emp-container .email-text').val('');
        $('#view-emp-popup .edit-emp-container .contact-no-text').val('');
        $('#employees-tab .emp-list').find('.emp-viewed').removeClass('emp-viewed');
        $('#view-emp-popup .btn-edit-emp').addClass('btn-default');
        $('#view-emp-popup .btn-edit-emp').removeClass('btn-primary');
        $('#view-emp-popup .btn-edit-emp').text('');
        $('#view-emp-popup .btn-edit-emp').append('<span class="glyphicon glyphicon-edit"></span> Edit');
        $('#view-emp').text('View Employee');
        $('#view-emp-popup .btn-update').addClass('hide');
        $('#view-emp-popup .edit-emp-container').addClass('hide');
        $('#view-emp-popup .view-emp-container').removeClass('hide');
        $('#new-emp-popup select.error').removeClass('error');
        $('#new-emp-popup input.error').removeClass('error');
        $('#new-emp-popup label.error').remove();
    });
    // upadte employee
    $('#view-emp-popup #emp-edit-form').validate({
        rules: {
            lname: 'required',
            fname: 'required',
            mname: 'required',
            date_emp: {
                required: true,
                date: true,
            },
            email_1: 'email',
            email_2: 'email',
            contact_no_1: {
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
            contact_no_2: {
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
            contact_no_3: {
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
        },
        groups: {
            bday: 'bday_month bday_day bday_year'
        },
        errorPlacement: function(error, element) {
            var name = element.prop('name');
            if (name === 'bday_month' || name === 'bday_day' || name === 'bday_year') {
                error.insertAfter('#view-emp-popup .bday');
            } else {
                error.insertAfter(element);
            }
        },
        submitHandler: function(form) {
            var address = new Array();
            var email = new Array();
            var contact = new Array();
            $('#view-emp-popup .edit-emp-container .address-container .address-text').each(function() {
                if ($(this).val() != '') {
                    address.push($(this).val());
                }
            });
            $('#view-emp-popup .edit-emp-container .email-container .email-text').each(function() {
                if ($(this).val() != '') {
                    email.push($(this).val());
                }
            });
            $('#view-emp-popup .edit-emp-container .contact-no-container .contact-no-text').each(function() {
                if ($(this).val() != '') {
                    contact.push($(this).val());
                }
            });
            var emp = {
                'emp_id': $('#view-emp-popup #emp-id').val(),
                'lname': $('#view-emp-popup .edit-emp-container .lname').val(),
                'fname': $('#view-emp-popup .edit-emp-container .fname').val(),
                'mname': $('#view-emp-popup .edit-emp-container .mname').val(),
                'bday': $('#view-emp-popup .bday-year').val() + '-' + $('#view-emp-popup .bday-month').val() + '-' + $('#view-emp-popup .bday-day').val(),
                'gender': $('#view-emp-popup .edit-emp-container .gender .active input').val(),
                'date_emp': $('#view-emp-popup .edit-emp-container .date-emp').val(),
                'address': address.join(';'),
                'email': email.join(';'),
                'contact_no': contact.join(';'),
                'action': 1,
            };
            save_emp(emp, $('#view-emp-popup').attr('id'));
            return false;
        },
    });
    // delete employees
    $('.emp-list .check-all-emp').click(function() {
        if ($(this).is(':checked')) {
            if ($('.emp-list tr td input[type=checkbox]').hasClass('item-emp-checkbox')) {
                $('.btn-delete-emp').removeClass('hide-element');
                $('.emp-list tr td input[type=checkbox]').prop('checked', true);
            } else {
                $('.btn-delete-emp').addClass('hide-element');
                $(this).prop('checked', false);
            }
        } else {
            $('.btn-delete-emp').addClass('hide-element');
            $('.emp-list tr td input[type=checkbox]').prop('checked', false);
        }
    });
    $('.emp-list').on('click', '.item-emp-checkbox', function() {
        var $checked_item = $('.emp-list .item-emp-checkbox:checked').size();
        if ($(this).is(':checked')) {
            $('.btn-delete-emp').removeClass('hide-element');
        } else {
            if ($checked_item > 0) {
                $('.btn-delete-emp').removeClass('hide-element');
            } else {
                $('.btn-delete-emp').addClass('hide-element');
                $('.emp-list .check-all-emp').prop('checked', false);
            }
        }
    });
    $('#delete-emp-popup .btn-yes').click(function() {
        var empId = new Array();
        $('.emp-list .item-emp-checkbox:checked').each(function() {
            empId.push($(this).val());
        });
        var type = {'emp_id': empId};
        $.ajax({
            url: $url + 'employee/delete',
            type: 'post',
            data: type,
            dataType: 'json',
            success: function(data) {
                $('#delete-emp-popup').modal('hide');
                $('.alert-danger').remove();
                $('.alert-success').remove();
                $('.contacts-container').prepend('<div class="alert alert-success margin-top">' + data.msg + '</div>');
                var $table = $('#employees-table').dataTable();
                $('.employees-list .item-employee-checkbox:checked').each(function() {
                    $table.fnDeleteRow($table.fnGetPosition($(this).closest('tr')[0]));
                });
                refresh_employees_table();
                success_msg();
                $('.emp-list .check-all-emp').prop('checked', false);
                $('.emp-list .item-emp-checkbox:checked').parent().parent().remove();
                $('.btn-delete-emp').addClass('hide-element');
            },
            error: function() {
                $('#delete-emp-popup').modal('hide');
                $('.alert-danger').remove();
                $('.alert-success').remove();
                $('.contacts-container').prepend('<div class="alert alert-success margin-top">Something went  wrong while deleting employee/s. Please try again later.</div>');
                error_msg();
            }
        });
    });
    //Clients-------------------------------------------------------------------
    $('#clients-table').dataTable({
        "aoColumnDefs": [{
                "bSortable": false,
                "aTargets": [0]}],
    });
    // new client
    $('#new-client-popup #client-form').validate({
        rules: {
            lname: 'required',
            fname: 'required',
            address_1: 'required',
            email_1: {
                required: true,
                email: true,
            },
            email_2: {
                email: true,
            },
            contact_no_1: {
                required: true,
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
            contact_no_2: {
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
            contact_no_3: {
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
        },
        submitHandler: function(form) {
            var address = new Array();
            var email = new Array();
            var contact = new Array();
            $('#new-client-popup .address-container .address-text').each(function() {
                if ($(this).val() != '') {
                    address.push($(this).val());
                }
            });
            $('#new-client-popup .email-container .email-text').each(function() {
                if ($(this).val() != '') {
                    email.push($(this).val());
                }
            });
            $('#new-client-popup .contact-no-container .contact-no-text').each(function() {
                if ($(this).val() != '') {
                    contact.push($(this).val());
                }
            });
            var client = {
                'lname': $('#new-client-popup .lname').val(),
                'fname': $('#new-client-popup .fname').val(),
                'address': address.join(';'),
                'email': email.join(';'),
                'contact_no': contact.join(';'),
                'action': 0,
            };
            save_client(client, $('#new-client-popup').attr('id'));
            return false;
        }
    });
    $('#new-client-popup').on('hide.bs.modal', function() {
        $('#new-client-popup .lname').val('');
        $('#new-client-popup .fname').val('');
        $('#new-client-popup .address-text').val('');
        $('#new-client-popup .email-text').val('');
        $('#new-client-popup .contact-no-text').val('');
        $('#new-client-popup input.error').removeClass('error');
        $('#new-client-popup label.error').remove();
    });
    // view/edit client
    $('#view-client-popup').on('click', '.btn-edit-client', function() {
        if ($(this).text() == ' Cancel Editing') {
            $(this).addClass('btn-default');
            $(this).removeClass('btn-primary');
            $(this).text('');
            $(this).append('<span class="glyphicon glyphicon-edit"></span> Edit');
            $('#view-client').text('View Client');
            $('#view-client-popup .btn-update').addClass('hide');
            $('#view-client-popup .edit-client-container').addClass('hide');
            $('#view-client-popup .view-client-container').removeClass('hide');
        } else {
            $(this).removeClass('btn-default');
            $(this).addClass('btn-primary');
            $(this).text('');
            $(this).append('<span class="glyphicon glyphicon-edit"></span> Cancel Editing');
            $('#view-client').text('Edit Client');
            $('#view-client-popup .btn-update').removeClass('hide');
            $('#view-client-popup .edit-client-container').removeClass('hide');
            $('#view-client-popup .view-client-container').addClass('hide');
        }
    });
    $('.client-list').on('click', '.btn-view-client', function() {
        $('#view-client-popup #client-id').val($(this).parent().siblings().children().val());
    });
    $('#view-client-popup').on('show.bs.modal', function() {
        var $clientId = $('#view-client-popup #client-id').val();
        get_client($clientId);
    });
    $('#view-client-popup #client-edit-form').validate({
        rules: {
            lname: 'required',
            fname: 'required',
            address_1: 'required',
            email_1: {
                required: true,
                email: true,
            },
            email_2: {
                email: true,
            },
            contact_no_1: {
                required: true,
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
            contact_no_2: {
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
            contact_no_3: {
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
        },
        submitHandler: function(form) {
            var address = new Array();
            var email = new Array();
            var contact = new Array();
            $('#view-client-popup .edit-client-container .address-container .address-text').each(function() {
                if ($(this).val() != '') {
                    address.push($(this).val());
                }
            });
            $('#view-client-popup .edit-client-container .email-container .email-text').each(function() {
                if ($(this).val() != '') {
                    email.push($(this).val());
                }
            });
            $('#view-client-popup .edit-client-container .contact-no-container .contact-no-text').each(function() {
                if ($(this).val() != '') {
                    contact.push($(this).val());
                }
            });
            var client = {
                'client_id': $('#view-client-popup #client-id').val(),
                'lname': $('#view-client-popup .edit-client-container .lname').val(),
                'fname': $('#view-client-popup .edit-client-container .fname').val(),
                'address': address.join(';'),
                'email': email.join(';'),
                'contact_no': contact.join(';'),
                'action': 1,
            };
            save_client(client, $('#view-client-popup').attr('id'));
            return false;
        }
    });
    $('#view-client-popup').on('hide.bs.modal', function() {
        $('#view-client-popup .edit-client-container .lname').val('');
        $('#view-client-popup .edit-client-container .fname').val('');
        $('#view-client-popup .edit-client-container .address-text').val('');
        $('#view-client-popup .edit-client-container .email-text').val('');
        $('#view-client-popup .edit-client-container .contact-no-text').val('');
        $('.client-list').find('.client-viewed').removeClass('client-viewed');
        $('#view-client-popup .btn-edit-client').addClass('btn-default');
        $('#view-client-popup .btn-edit-client').removeClass('btn-primary');
        $('#view-client-popup .btn-edit-client').text('');
        $('#view-client-popup .btn-edit-client').append('<span class="glyphicon glyphicon-edit"></span> Edit');
        $('#view-client').text('View Client');
        $('#view-client-popup .btn-update').addClass('hide');
        $('#view-client-popup .edit-client-container').addClass('hide');
        $('#view-client-popup .view-client-container').removeClass('hide');
        $('#view-client-popup input.error').removeClass('error');
        $('#view-client-popup label.error').remove();
    });
    // delete clients
    $('.client-list .check-all-client').click(function() {
        if ($(this).is(':checked')) {
            if ($('.client-list tr td input[type=checkbox]').hasClass('item-client-checkbox')) {
                $('.btn-delete-client').removeClass('hide-element');
                $('.client-list tr td input[type=checkbox]').prop('checked', true);
            } else {
                $('.btn-delete-client').addClass('hide-element');
                $(this).prop('checked', false);
            }
        } else {
            $('.btn-delete-client').addClass('hide-element');
            $('.client-list tr td input[type=checkbox]').prop('checked', false);
        }
    });
    $('.client-list').on('click', '.item-client-checkbox', function() {
        var $checked_item = $('.client-list .item-client-checkbox:checked').size();
        if ($(this).is(':checked')) {
            $('.btn-delete-client').removeClass('hide-element');
        } else {
            if ($checked_item > 0) {
                $('.btn-delete-client').removeClass('hide-element');
            } else {
                $('.btn-delete-client').addClass('hide-element');
                $('.client-list .check-all-client').prop('checked', false);
            }
        }
    });
    $('#delete-client-popup .btn-yes').click(function() {
        var clientId = new Array();
        $('.client-list .item-client-checkbox:checked').each(function() {
            clientId.push($(this).val());
        });
        var client = {'client_id': clientId};
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'client/delete',
            type: 'post',
            data: client,
            dataType: 'json',
            success: function(data) {
                $('#delete-client-popup').modal('hide');
                $('.alert-danger').remove();
                $('.alert-success').remove();
                $('.contacts-container').prepend('<div class="alert alert-success margin-top">' + data.msg + '</div>');
                var $table = $('#clients-table').dataTable();
                $('.clients-list .item-client-checkbox:checked').each(function() {
                    $table.fnDeleteRow($table.fnGetPosition($(this).closest('tr')[0]));
                });
                refresh_clients_table();
                success_msg();
                $('.client-list .check-all-client').prop('checked', false);
                $('.client-list .item-client-checkbox:checked').parent().parent().remove();
                $('.btn-delete-client').addClass('hide-element');
                $('.loading-container').addClass('hide');
            },
            error: function() {
                $('#delete-client-popup').modal('hide');
                $('.alert-danger').remove();
                $('.alert-success').remove();
                $('.contacts-container').prepend('<div class="alert alert-success margin-top">Something went wrong while deleting the client/s. Please try again later.</div>');
                error_msg();
                $('.loading-container').addClass('hide');
            }
        });
    });
    //Supplier------------------------------------------------------------------
    $('#supplier-table').dataTable({
        "aoColumnDefs": [{
                "bSortable": false,
                "aTargets": [0]}],
    });
    // new supplier
    $('#new-supplier-popup .new-supplier-container .another-services').click(function() {
        new_services_row($('#new-supplier-popup').attr('id'), 'new-supplier-container');
    });
    $('#new-supplier-popup').on('click', '.btn-remove-services', function() {
        $(this).parent().parent().remove();
    });
    $('#new-supplier-popup #supplier-form').validate({
        rules: {
            cname: 'required',
            contact_person: 'required',
            address_1: 'required',
            email_1: {
                required: true,
                email: true,
            },
            email_2: 'email',
            contact_no_1: {
                required: true,
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
            contact_no_2: {
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
            contact_no_3: {
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
        },
        submitHandler: function(form) {
            var services = new Array();
            var address = new Array();
            var email = new Array();
            var contact = new Array();
            $('#new-supplier-popup .services-container .services-text').each(function() {
                if ($(this).val() != '') {
                    services.push($(this).val());
                }
            });
            $('#new-supplier-popup .address-container .address-text').each(function() {
                if ($(this).val() != '') {
                    address.push($(this).val());
                }
            });
            $('#new-supplier-popup .email-container .email-text').each(function() {
                if ($(this).val() != '') {
                    email.push($(this).val());
                }
            });
            $('#new-supplier-popup .contact-no-container .contact-no-text').each(function() {
                if ($(this).val() != '') {
                    contact.push($(this).val());
                }
            });
            var supplier = {
                'cname': $('#new-supplier-popup .cname').val(),
                'contact_person': $('#new-supplier-popup .contact-person').val(),
                'services': services.join(';'),
                'address': address.join(';'),
                'email': email.join(';'),
                'contact_no': contact.join(';'),
                'action': 0,
            };
            save_supplier(supplier, $('#new-supplier-popup').attr('id'));
            return false;
        }
    });
    $('#new-supplier-popup').on('hide.bs.modal', function() {
        $('#new-supplier-popup .cname').val('');
        $('#new-supplier-popup .contact-person').val('');
        $('#new-supplier-popup .services-text').val('');
        $('#new-supplier-popup .address-text').val('');
        $('#new-supplier-popup .email-text').val('');
        $('#new-supplier-popup .contact-no-text').val('');
        $('#new-supplier-popup .services-container').find('.d-services').parent().remove();
        $('#new-supplier-popup input.error').removeClass('error');
        $('#new-supplier-popup label.error').remove();
    });
    // view/edit supplier
    $('#view-supplier-popup').on('click', '.btn-edit-supplier', function() {
        if ($(this).text() == ' Cancel Editing') {
            $(this).addClass('btn-default');
            $(this).removeClass('btn-primary');
            $(this).text('');
            $(this).append('<span class="glyphicon glyphicon-edit"></span> Edit');
            $('#view-supplier').text('View Supplier');
            $('#view-supplier-popup .btn-update').addClass('hide');
            $('#view-supplier-popup .edit-supplier-container').addClass('hide');
            $('#view-supplier-popup .view-supplier-container').removeClass('hide');
        } else {
            $(this).removeClass('btn-default');
            $(this).addClass('btn-primary');
            $(this).text('');
            $(this).append('<span class="glyphicon glyphicon-edit"></span> Cancel Editing');
            $('#view-supplier').text('Edit Supplier');
            $('#view-supplier-popup .btn-update').removeClass('hide');
            $('#view-supplier-popup .edit-supplier-container').removeClass('hide');
            $('#view-supplier-popup .view-supplier-container').addClass('hide');
        }
    });
    $('#view-supplier-popup .edit-supplier-container .another-services').click(function() {
        new_services_row($('#view-supplier-popup').attr('id'), 'edit-supplier-container');
    });
    $('#view-supplier-popup').on('click', '.btn-remove-services', function() {
        $(this).parent().parent().remove();
    });
    $('.supplier-list').on('click', '.btn-view-supplier', function() {
        $('#view-supplier-popup #supplier-id').val($(this).parent().siblings().children().val());
    });
    $('#view-supplier-popup').on('show.bs.modal', function() {
        var $supplierId = $('#view-supplier-popup #supplier-id').val();
        get_supplier($supplierId);
    });
    $('#view-supplier-popup #supplier-edit-form').validate({
        rules: {
            cname: 'required',
            contact_person: 'required',
            address_1: 'required',
            email_1: {
                required: true,
                email: true,
            },
            email_2: 'email',
            contact_no_1: {
                required: true,
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
            contact_no_2: {
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
            contact_no_3: {
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
        },
        submitHandler: function(form) {
            var services = new Array();
            var address = new Array();
            var email = new Array();
            var contact = new Array();
            $('#view-supplier-popup .edit-supplier-container .services-container .services-text').each(function() {
                if ($(this).val() != '') {
                    services.push($(this).val());
                }
            });
            $('#view-supplier-popup .edit-supplier-container .address-container .address-text').each(function() {
                if ($(this).val() != '') {
                    address.push($(this).val());
                }
            });
            $('#view-supplier-popup .edit-supplier-container .email-container .email-text').each(function() {
                if ($(this).val() != '') {
                    email.push($(this).val());
                }
            });
            $('#view-supplier-popup .edit-supplier-container .contact-no-container .contact-no-text').each(function() {
                if ($(this).val() != '') {
                    contact.push($(this).val());
                }
            });
            var supplier = {
                'supplier_id': $('#view-supplier-popup #supplier-id').val(),
                'cname': $('#view-supplier-popup .edit-supplier-container .cname').val(),
                'contact_person': $('#view-supplier-popup .edit-supplier-container .contact-person').val(),
                'services': services.join(';'),
                'address': address.join(';'),
                'email': email.join(';'),
                'contact_no': contact.join(';'),
                'action': 1,
            };
            save_supplier(supplier, $('#view-supplier-popup').attr('id'));
            return false;
        }
    });
    $('#view-supplier-popup').on('hide.bs.modal', function() {
        $('#view-supplier-popup .edit-supplier-container .cname').val('');
        $('#view-supplier-popup .edit-supplier-container .contact-person').val('');
        $('#view-supplier-popup .edit-supplier-container .services-text').val('');
        $('#view-supplier-popup .edit-supplier-container .address-text').val('');
        $('#view-supplier-popup .edit-supplier-container .email-text').val('');
        $('#view-supplier-popup .edit-supplier-container .contact-no-text').val('');
        $('#view-supplier-popup .services-container .d-services').remove();
        $('#view-supplier-popup .services-container .services-d').parent().remove();
        $('.supplier-list').find('.supplier-viewed').removeClass('supplier-viewed');
        $('#view-supplier-popup .btn-edit-supplier').addClass('btn-default');
        $('#view-supplier-popup .btn-edit-supplier').removeClass('btn-primary');
        $('#view-supplier-popup .btn-edit-supplier').text('');
        $('#view-supplier-popup .btn-edit-supplier').append('<span class="glyphicon glyphicon-edit"></span> Edit');
        $('#view-supplier').text('View Supplier');
        $('#view-supplier-popup .btn-update').addClass('hide');
        $('#view-supplier-popup .edit-supplier-container').addClass('hide');
        $('#view-supplier-popup .view-supplier-container').removeClass('hide');
        $('#view-supplier-popup input.error').removeClass('error');
        $('#view-supplier-popup label.error').remove();
    });
    // delete supplier
    $('.supplier-list .check-all-supplier').click(function() {
        if ($(this).is(':checked')) {
            if ($('.supplier-list tr td input[type=checkbox]').hasClass('item-supplier-checkbox')) {
                $('.btn-delete-supplier').removeClass('hide-element');
                $('.supplier-list tr td input[type=checkbox]').prop('checked', true);
            } else {
                $('.btn-delete-supplier').addClass('hide-element');
                $(this).prop('checked', false);
            }
        } else {
            $('.btn-delete-supplier').addClass('hide-element');
            $('.supplier-list tr td input[type=checkbox]').prop('checked', false);
        }
    });
    $('.supplier-list').on('click', '.item-supplier-checkbox', function() {
        var $checked_item = $('.client-list .item-supplier-checkbox:checked').size();
        if ($(this).is(':checked')) {
            $('.btn-delete-supplier').removeClass('hide-element');
        } else {
            if ($checked_item > 0) {
                $('.btn-delete-supplier').removeClass('hide-element');
            } else {
                $('.btn-delete-supplier').addClass('hide-element');
                $('.supplier-list .check-all-supplier').prop('checked', false);
            }
        }
    });
    $('#delete-supplier-popup .btn-yes').click(function() {
        var supplier_id = new Array();
        $('.supplier-list .item-supplier-checkbox:checked').each(function() {
            supplier_id.push($(this).val());
        });
        var supplier = {'supplier_id': supplier_id};
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'supplier/delete',
            type: 'post',
            data: supplier,
            success: function() {
                $('#delete-supplier-popup').modal('hide');
                $('.alert-danger').remove();
                $('.alert-success').remove();
                $('.contacts-container').prepend('<div class="alert alert-success margin-top">Supplier successfully deleted.</div>');
                var $table = $('#supplier-table').dataTable();
                $('.supplier-list .item-supplier-checkbox:checked').each(function() {
                    $table.fnDeleteRow($table.fnGetPosition($(this).closest('tr')[0]));
                });
                refresh_supplier_table();
                success_msg();
                $('.supplier-list .check-all-supplier').prop('checked', false);
                $('.supplier-list .item-supplier-checkbox:checked').parent().parent().remove();
                $('.btn-delete-supplier').addClass('hide-element');
                $('.loading-container').addClass('hide');
            },
            error: function() {
                $('#delete-supplier-popup').modal('hide');
                $('.alert-danger').remove();
                $('.alert-success').remove();
                $('.contacts-container').prepend('<div class="alert alert-danger margin-top">Something went wrong while deleting the supplier. Please try again later.</div>');
                error_msg();
                $('.loading-container').addClass('hide');
            }
        });
    });
    //Event Calendar------------------------------------------------------------
    $('#event-calendar').on('click', '.view-event-from-calendar', function() {
        $('#view-event-calendar-popup #event-id').val($(this).attr('data-eventid'));
    });
    // View Event---------------------------------------------------------------
    $('#view-event-calendar-popup').on('show.bs.modal', function() {
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'event/get',
            type: 'post',
            data: {'event': $('#view-event-calendar-popup #event-id').val()},
            dataType: 'json',
            success: function(data) {
                var date = data.event.actual_date_time.split(' ');
                var actualDate = date[0].split('-');
                var time = date[1].split(':');
                var day = actualDate[2].split(' ');
                var loc = new Array();
                var actualMonth;
                $.each(data.event_venue, function(key, value) {
                    loc.push(value.venue_name + ' ('+value.venue_address+')');
                    $('#view-event-calendar-popup #update-event-details-form .venue-panel').append('<label>' +
                            '<input type="checkbox" class="venue-checkbox" checked value="' + value.venue_id + '" /> ' +
                            value.venue_name +' ('+ value.venue_address +')</label> ');
                });
                switch (actualDate[1]) {
                    case '01':
                        actualMonth = 'January';
                        break;
                    case '02':
                        actualMonth = 'February';
                        break;
                    case '03':
                        actualMonth = 'March';
                        break;
                    case '04':
                        actualMonth = 'April';
                        break;
                    case '05':
                        actualMonth = 'May';
                        break;
                    case '06':
                        actualMonth = 'June';
                        break;
                    case '07':
                        actualMonth = 'July';
                        break;
                    case '08':
                        actualMonth = 'August';
                        break;
                    case '09':
                        actualMonth = 'September';
                        break;
                    case '10':
                        actualMonth = 'October';
                        break;
                    case '11':
                        actualMonth = 'November';
                        break;
                    case '12':
                        actualMonth = 'December';
                        break;
                    default:
                        actualMonth = '';
                }
                $('#view-event-calendar-popup #view-event-title').text(data.event.event_name);

                if (data.event.event_status == 0) {
                    $('#view-event-calendar-popup .btn-terminate-event').remove();
                    $('#view-event-calendar-popup .btn-cancel-event').remove();
                    $('#view-event-calendar-popup #view-event-title').after('<button class="btn btn-primary btn-terminate-event" style="margin-left:0.5em;margin-right:0.5em">Terminate Event</button> ');
                    $('#view-event-calendar-popup #view-event-title').after('<button class="btn btn-primary btn-cancel-event">Cancel Event</button>');
                }
                $('#view-event-details-tab .view-event-details-container .event-name').text(data.event.event_name);
                $('#view-event-details-tab .view-event-details-container .event-type').text(data.event.type_name);
                $('#view-event-details-tab .view-event-details-container .event-budget').text(data.event.initial_budget);
                if (data.event_client === false) {
                    $('#view-event-details-tab .view-event-details-container .event-client').text('No client specified.');
                } else {
                    $('#view-event-details-tab .view-event-details-container .event-client').text(data.event_client.client_lname + ', ' + data.event_client.client_fname);
                }
                $('#view-event-details-tab .view-event-details-container .start-date').text(data.event.start_date);
                $('#view-event-details-tab .view-event-details-container .end-date').text(data.event.end_date);
                $('#view-event-details-tab .view-event-details-container .actual-date').text(data.event.actual_date_time);
                $('#view-event-details-tab .view-event-details-container .event-loc').text(loc.join(';'));
                $('#view-event-details-tab .view-event-details-container .event-coord').text(data.event_coord.coord_fname + ' ' +
                        data.event_coord.coord_mname + ' ' + data.event_coord.coord_lname);
                $('#view-event-details-tab .view-event-details-container .event-notes').text(data.event.event_description);
                $('#view-event-details-tab .view-event-details-container .a-d-yr').text(actualDate[0]);
                $('#view-event-details-tab .view-event-details-container .a-d-day').text(day[0]);
                $('#view-event-details-tab .view-event-details-container .a-d-month').text(actualMonth);
                // edit event details
                $('#view-event-calendar-popup #update-event-details-form .event-name').val(data.event.event_name);
                $('#view-event-calendar-popup #update-event-details-form .event-type-select option[value=' +
                        data.event.type_id + ']').prop('selected', true);
                $('#view-event-calendar-popup #update-event-details-form .event-budget').val(data.event.initial_budget);
                $('#view-event-calendar-popup #update-event-details-form .client-select').empty().prepend('<option value="">Client</option>');
                if (data.event_client === false) {
                    $('#view-event-calendar-popup #update-event-details-form .client-select option[value=""]').prop('selected', true);
                } else {
                    $('#view-event-calendar-popup #update-event-details-form .client-select').append('<option value="' +
                            data.event_client.client_id + '">' + data.event_client.client_lname + ', ' + data.event_client.client_fname + '</option>');
                    $('#view-event-calendar-popup #update-event-details-form .client-select option[value=' +
                            data.event_client.client_id + ']').prop('selected', true);
                }
                $('#view-event-calendar-popup #update-event-details-form .start-date').val(data.event.start_date);
                $('#view-event-calendar-popup #update-event-details-form .end-date').val(data.event.end_date);
                $('#view-event-calendar-popup #update-event-details-form .coordinator-select option[value=' +
                        data.event_coord.coordinator_id + ']').prop('selected', true);
                $('#view-event-calendar-popup #update-event-details-form .a-hr option[value=' +
                        time[0] + ']').prop('selected', true);
                $('#view-event-calendar-popup #update-event-details-form .a-min option[value=' +
                        time[1] + ']').prop('selected', true);
                $('#view-event-calendar-popup #update-event-details-form .actual-date').val(date[0]);
                $('#view-event-details-tab #update-event-details-form .event-desc').val(data.event.event_description);
                $('#update-event-details-form .all-venues .venue-select .default-venue').siblings().remove();
                $.each(data.venues, function(key, value){
                    $('#update-event-details-form .all-venues .venue-select .default-venue').
                            after('<option value="'+value.venue_id+'">'+value.venue_name+' ('+value.venue_address+')</option>');
                });
                // view and update event supplier
                $('#view-event-supplier-tab .assigned-event-supplier-container').empty();
                $.each(data.event_supplier, function(key, value) {
                    $('#view-event-supplier-tab .assigned-event-supplier-container').
                            append('<div class="list-group" style="padding:1%;border: solid 1px #cccccc;background-color:#99ff99;position:relative">' +
                            '<div class="view-supplier-services hide"><div class="panel"><div class="panel-body"></div></div><div class="pull-right">' +
                            '<button type="button" class="btn btn-default btn-cancel">Cancel</button> ' +
                            '<button type="button" class="btn btn-primary btn-assign">Assign</button>' +
                            '</div>' +
                            '<div class="clearfix"></div></div>' +
                            '<div class="e-s-container">' +
                            '<h4 class="list-group-item-heading">Company Name: <span class="company-name">' + value.company + '</span></h4>' +
                            '<p class="list-group-item-text">Contact Person: ' + value.contact_person + '</p>' +
                            '<p class="list-group-item-text">Contact No.: ' + value.s_num + '</p>' +
                            '<p class="list-group-item-text">Available Services: <span class="available-services">' + value.services + '</span></p>' +
                            '<p class="list-group-item-text">Services chosen: <span class="services-chosen">' + value.event_svc + '</span></p>' +
                            '<div class="btn-group pull-right">' +
                            '<a href="#services-popup" data-toggle="modal" class="btn-assign-services" data-supplierid="' + value.supplier_id + '">Services</a>' +
                            '<span class="separator"> | </span><a class="unassign-supplier">Unasign supplier</a>' +
                            '</div><div class="clearfix"></div></div></div>');
                });
                // event checklist
                $('#view-event-checklist-tab .checklist-list').empty();
                $('#view-event-checklist-tab .checklist-list').append('<div class="table-responsive">   ' +
                        '<table id="event-checklist" class="table table-hover event-checklist">' +
                        '<thead>' +
                        '<tr>' +
                        '<th style="width: 50%;">Items</th>' +
                        '<th style="width: 1%;">Status</th>' +
                        '<th style="width: 44%;">Remarks</th>' +
                        '</tr>' +
                        '</thead>' +
                        '<tbody>' +
                        '</tbody>' +
                        '</table>' +
                        '<div class="pull-right"><button class="btn btn-primary btn-update">Update</button></div>' +
                        '<div class="clearfix"></div>' +
                        '</div>');
                $.each(data.event_checklist, function(key, value) {
                    var remarks;
                    if (value.ch_remarks === null) {
                        remarks = '';
                    } else {
                        remarks = value.ch_remarks;
                    }
                    if (value.checklist_status == '0') {
                        $('#view-event-checklist-tab .checklist-list tbody').append('<tr>' +
                                '<td>' + value.list_description + '</td>' +
                                '<td><input type="checkbox" name="checklist_status" class="checklist-checkbox" value="' + value.checklist_id + '" /></td>' +
                                '<td><textarea class="checklist-remarks" style="width:100%">' + remarks + '</textarea></td>' +
                                '</tr>');
                    } else {
                        $('#view-event-checklist-tab .checklist-list tbody').append('<tr>' +
                                '<td>' + value.list_description + '</td>' +
                                '<td><input type="checkbox" name="checklist_status" class="checklist-checkbox" checked value="' + value.checklist_id + '" /></td>' +
                                '<td><textarea class="checklist-remarks" style="width:100%">' + remarks + '</textarea></td>' +
                                '</tr>');
                    }
                });
                $('#view-event-checklist-tab #new-checklist-item-form .category-select .default-val').siblings().empty();
                $.each(data.category, function(key, value) {
                    $('#view-event-checklist-tab #new-checklist-item-form .category-select').
                            append('<option value="' + value.category_id + '">' + value.category_name + '</option>');
                });
                // task
                $('#view-event-calendar-popup #task-list').empty();
                if(data.task!==false){
                    $.each(data.task, function(key, value) {
                        $('#view-task-tab #task-list').prepend('<div class="list-group col-md-6" style="padding:1em;border: solid 1px #cccccc;" data-taskid="' +
                                value.task_id + '"><p class="list-group-item-text">Task: <span class="task-desc">' + value.task_desc + '</span></p>' +
                                '<p class="list-group-item-text">Date and Time: <span class="task-date">' + value.task_date + '</span> ' +
                                '<span class="task-time">' + value.task_time + '</span></p>' +
                                '<div class="btn-group pull-right">' +
                                '<a class="btn-remove-task" data-taskid="' + value.task_id + '">Remove task</a>' +
                                '</div><div class="clearfix"></div></div>');
                    });
                }else{
                    $('#view-event-calendar-popup #task-list').append('<div class="alert alert-info">You dont have anymore task to do. :D</div>');
                }
                // production schedule
                $("#new-schedule-btn").addClass('hide');
                $("#update-schedule-btn").addClass('hide');
                $("#export-schedule-btn").addClass('hide');
                $("#pdf-schedule-btn").addClass('hide');
                get_schedule(getEID());
                // expenses
                refresh_expense_table($('#view-event-calendar-popup #event-id').val());
                post_event_budget(getEID());
                post_exp_actual_amount(getEID());
                post_balance(getEID());

                // voucher
                refresh_voucher_table($('#view-event-calendar-popup #event-id').val());
                post_cv_amount(getEID());
                $('.loading-container').addClass('hide');
            },
            error: function(xhr, status) {
                $('.loading-container').addClass('hide');
            }
        });
    });
    // close event modal
    $('#view-event-calendar-popup').on('hide.bs.modal', function() {
        $('#view-event-nav li:eq(0) a').tab('show');
        $('#view-event-details-tab .btn-edit-event-details').html('<span class="glyphicon glyphicon-edit"></span> Edit');
        $('#view-event-details-tab .btn-edit-event-details').addClass('btn-default');
        $('#view-event-details-tab .btn-edit-event-details').removeClass('btn-primary');
        $('#view-event-details-tab .view-event-details-container').removeClass('hide');
        $('#view-event-details-tab .edit-event-details-container').addClass('hide');
        $('#view-event-details-tab .new-e-t-container').addClass('hide').siblings('.form-sep').remove();
        $('#view-event-details-tab .new-e-c-container').addClass('hide').siblings('.form-sep').remove();
        $('#view-event-details-tab .new-e-v-container').addClass('hide').siblings('.form-sep').remove();
        $('#view-event-details-tab .new-e-e-container').addClass('hide').siblings('.form-sep').remove();
        $('#update-event-details-form .all-venues').addClass('hide');
        $('#update-event-details-form .venue-select .default-venue').prop('selected', true);
        
    });
    // terminate event 
    $('#view-event-calendar-popup #view-event-title').on('click', '.btn-terminate-event', function() {
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'event/terminate',
            type: 'post',
            data: {'event': $('#modal-event-calendar #event-id').val()},
            dataType: 'json',
            success: function(data) {
                if (data === 'success') {
                    window.location = $url + 'events/calendar/' + yr + '/' + month;
                    $('.loading-container').addClass('hide');
                }
            },
            error: function(xhr, status) {
                $('.loading-container').addClass('hide');
            }
        });
    });
    // cancel event 
    $('#view-event-calendar-popup #view-event-title').on('click', '.btn-cancel-event', function() {
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'event/cancel',
            type: 'post',
            data: {'event': $('#modal-event-calendar #event-id').val()},
            dataType: 'json',
            success: function(data) {
                if (data === 'success') {
                    window.location = $url + 'events/calendar/' + yr + '/' + month;
                    $('.loading-container').addClass('hide');
                }
            },
            error: function(xhr, status) {
                $('.loading-container').addClass('hide');
            }
        });
    });
    //edit event details
    $('#view-event-details-tab .btn-edit-event-details').click(function() {
        if ($(this).text().trim() === 'Edit') {
            $(this).html('<span class="glyphicon glyphicon-edit"></span> Cancel editing');
            $(this).removeClass('btn-default');
            $(this).addClass('btn-primary');
            $('#view-event-details-tab .view-event-details-container').addClass('hide');
            $('#view-event-details-tab .edit-event-details-container').removeClass('hide');
        } else {
            $(this).html('<span class="glyphicon glyphicon-edit"></span> Edit');
            $(this).addClass('btn-default');
            $(this).removeClass('btn-primary');
            $('#view-event-details-tab .view-event-details-container').removeClass('hide');
            $('#view-event-details-tab .edit-event-details-container').addClass('hide');
        }
    });
    $('#update-event-details-form .assign-venue').click(function(){
        $('#update-event-details-form .all-venues').removeClass('hide');
    });
    $('#update-event-details-form .all-venues .btn-cancel').click(function(){
        $('#update-event-details-form .all-venues').addClass('hide');
        $('#update-event-details-form .venue-select .default-venue').prop('selected', true);
    });
    $('#update-event-details-form .all-venues .btn-assign').click(function(){
        var venue = $('#update-event-details-form .all-venues option:selected').text();
        var existing;
        $('#update-event-details-form .venue-panel label').each(function() {
            if ($(this).text().trim() === venue.trim()) {
                existing = true;
                return false;
            }
        });
        if (existing) {
            $('#update-event-details-form .venue-panel').parent().before('<div class="alert alert-danger margin-top">Venue already assigned.</div>');
            remove_alert();
        } else {
            $('#update-event-details-form .venue-panel').
                    prepend('<label><input type="checkbox" class="venue-checkbox" checked value="'+
                    $('#update-event-details-form .all-venues option:selected').val()+'"> '+
                    venue+'</label> ');
            $('#update-event-details-form .venue-select .default-venue').prop('selected', true);
        }
    });
    // show event type form
    $('#view-event-details-tab .new-e-t-link').click(function() {
        $('#view-event-details-tab .new-e-c-container').addClass('hide').siblings('.form-sep').remove();
        $('#view-event-details-tab .new-e-v-container').addClass('hide').siblings('.form-sep').remove();
        $('#view-event-details-tab .new-e-e-container').addClass('hide').siblings('.form-sep').remove();
        $('#view-event-details-tab .new-e-t-container').removeClass('hide')
                .after('<hr style="margin-top:0" class="form-sep">');
    });
    $('#view-event-details-tab .new-e-t-container .btn-cancel').click(function() {
        $('#view-event-details-tab .new-e-t-container').addClass('hide').siblings('.form-sep').remove();
        $('.edit-event-details-container #e-t-form .event-type-name').val('');
    });
    // new event type
    $('.edit-event-details-container #e-t-form').validate({
        rules: {
            event_type_name: 'required',
        },
        submitHandler: function(form) {
            $('.loading-container').removeClass('hide');
            $.ajax({
                url: $url + 'event-type/save',
                type: 'POST',
                dataType: 'json',
                data: {'event_type_name': $('.edit-event-details-container #e-t-form .event-type-name').val()},
                success: function(data) {
                    if (data.status === 'success') {
                        $('.edit-event-details-container #e-t-form .event-type-name').val('');
                        $('#view-event-details-tab .alert-success').remove();
                        $('#view-event-details-tab .alert-danger').remove();
                        $('#update-event-details-form .event-type-select').append('<option value="' + data.type.type_id + '">' + data.type.type_name + '</option>');
                        $('#view-event-details-tab .new-e-t-container').addClass('hide').siblings('.form-sep').remove();
                        $('#view-event-details-tab hr').after('<div class="alert alert-success margin-top">' + data.msg + '</div>');
                        success_msg();
                        $('.loading-container').addClass('hide');
                    } else {
                        if (data.type == 'already exist') {
                            $('#view-event-details-tab .alert-success').remove();
                            $('#view-event-details-tab .alert-danger').remove();
                            $('#view-event-details-tab hr').after('<div class="alert alert-danger margin-top">' + data.msg + '</div>');
                            error_msg();
                        } else {
                            $('.edit-event-details-container #e-t-form .event-type-name').val('');
                            $('#view-event-details-tab .alert-success').remove();
                            $('#view-event-details-tab .alert-danger').remove();
                            $('#view-event-details-tab hr').after('<div class="alert alert-danger margin-top">' + data.msg + '</div>');
                            error_msg();
                        }
                        $('.loading-container').addClass('hide');
                    }
                },
                error: function() {
                    $('.edit-event-details-container #e-t-form .event-type-name').val('');
                    $('#view-event-details-tab .alert-success').remove();
                    $('#view-event-details-tab .alert-danger').remove();
                    $('#view-event-details-tab .btn-edit-event-details').siblings().after('<div class="alert alert-danger margin-top">Something went wrong while saving the event type. Please try again later.</div>');
                    error_msg();
                    $('.loading-container').addClass('hide');
                }
            });
            return false;
        }
    });
    // show event client form
    $('#view-event-details-tab .new-e-c-link').click(function() {
        $('#view-event-details-tab .new-e-t-container').addClass('hide').siblings('.form-sep').remove();
        $('#view-event-details-tab .new-e-v-container').addClass('hide').siblings('.form-sep').remove();
        $('#view-event-details-tab .new-e-e-container').addClass('hide').siblings('.form-sep').remove();
        $('#view-event-details-tab .new-e-c-container').removeClass('hide')
                .after('<hr style="margin-top:0" class="form-sep">');
    });
    $('#view-event-details-tab .new-e-c-container .btn-cancel').click(function() {
        $('#view-event-details-tab .new-e-c-container').addClass('hide').siblings('.form-sep').remove();
        $('.edit-event-details-container #client-form .lname').val('');
        $('.edit-event-details-container #client-form .fname').val('');
        $('.edit-event-details-container #client-form .address-container .address-1').val('');
        $('.edit-event-details-container #client-form .address-container .address-2').val('').parent().addClass('hide');
        $('.edit-event-details-container #client-form .address-container .address-3').val('').parent().addClass('hide');
        $('.edit-event-details-container #client-form .email-container .email-1').val('');
        $('.edit-event-details-container #client-form .email-container .email-2').val('').parent().addClass('hide');
        $('.edit-event-details-container #client-form .contact-no-container .contact-1').val('');
        $('.edit-event-details-container #client-form .contact-no-container .contact-2').val('').parent().addClass('hide');
        $('.edit-event-details-container #client-form .contact-no-container .contact-3').val('').parent().addClass('hide');
        $('#view-event-details-tab .new-e-c-container label.error').remove();
        $('#view-event-details-tab .new-e-c-container input.error').removeClass('error');
    });
    // new client
    $('.edit-event-details-container #client-form').validate({
        rules: {
            lname: 'required',
            fname: 'required',
            address_1: 'required',
            email_1: {
                required: true,
                email: true,
            },
            email_2: {
                email: true,
            },
            contact_1: {
                required: true,
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
            contact_2: {
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
            contact_3: {
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
        },
        errorPlacement: function(error, element){
            var name = element.prop('name');
            if(name==='address_1'){
                $('.edit-event-details-container #client-form .address-container .address-1').after(error);
            }else if(name==='contact_1'){
                $('.edit-event-details-container #client-form .contact-no-container .contact-1').after(error);
            }else if(name==='contact_2'){
                $('.edit-event-details-container #client-form .contact-no-container .contact-2').parent().after(error);
            }else if(name==='contact_3'){
                $('.edit-event-details-container #client-form .contact-no-container .contact-3').parent().after(error);   
            }else if(name==='email_1'){
                $('.edit-event-details-container #client-form .email-container .email-1').after(error);   
            }else if(name==='email_2'){
                $('.edit-event-details-container #client-form .email-container .email-2').parent().after(error);   
            }else{
                error.insertAfter(element);
            }
        },
        submitHandler: function(form) {
            var address = new Array();
            var email = new Array();
            var contact = new Array();
            $('.edit-event-details-container #client-form .address-container .address-text').each(function() {
                if ($(this).val() != '') {
                    address.push($(this).val());
                }
            });
            $('.edit-event-details-container #client-form .email-container .email-text').each(function() {
                if ($(this).val() != '') {
                    email.push($(this).val());
                }
            });
            $('.edit-event-details-container #client-form .contact-no-container .contact-no-text').each(function() {
                if ($(this).val() != '') {
                    contact.push($(this).val());
                }
            });
            var client = {
                'lname': $('.edit-event-details-container #client-form .lname').val(),
                'fname': $('.edit-event-details-container #client-form .fname').val(),
                'address': address.join(';'),
                'email': email.join(';'),
                'contact_no': contact.join(';'),
                'action': 0,
            };
            save_client(client, $('#view-event-details-tab').attr('id'));
            return false;
        }
    });
    $('.edit-event-details-container #client-form .add-a-row').click(function() {
        if($('.edit-event-details-container #client-form .address-container .address-1').parent().hasClass('hide')){
            $('.edit-event-details-container #client-form .address-container .address-1').parent().removeClass('hide');
        }else if($('.edit-event-details-container #client-form .address-container .address-2').parent().hasClass('hide')){
            $('.edit-event-details-container #client-form .address-container .address-2').parent().removeClass('hide');
        }else if($('.edit-event-details-container #client-form .address-container .address-3').parent().hasClass('hide')){
            $('.edit-event-details-container #client-form .address-container .address-3').parent().removeClass('hide');
        }
    });
    $('.edit-event-details-container #client-form .address-container .btn-remove-row').click(function() {
        $(this).parent().siblings().val('');
        $(this).parent().parent().addClass('hide');
    });
    $('.edit-event-details-container #client-form .add-e-row').click(function() {
        if($('.edit-event-details-container #client-form .email-container .email-1').parent().hasClass('hide')){
            $('.edit-event-details-container #client-form .email-container .email-1').parent().removeClass('hide');
        }else if($('.edit-event-details-container #client-form .email-container .email-2').parent().hasClass('hide')){
            $('.edit-event-details-container #client-form .email-container .email-2').parent().removeClass('hide');
        }
    });
    $('.edit-event-details-container #client-form .email-container .btn-remove-row').click(function() {
        $(this).parent().siblings().val('');
        $(this).parent().parent().addClass('hide');
    });
    $('.edit-event-details-container #client-form .add-c-row').click(function() {
        if($('.edit-event-details-container #client-form .contact-no-container .contact-1').parent().hasClass('hide')){
            $('.edit-event-details-container #client-form .contact-no-container .contact-1').parent().removeClass('hide');
        }else if($('.edit-event-details-container #client-form .contact-no-container .contact-2').parent().hasClass('hide')){
            $('.edit-event-details-container #client-form .contact-no-container .contact-2').parent().removeClass('hide');
        }else if($('.edit-event-details-container #client-form .contact-no-container .contact-3').parent().hasClass('hide')){
            $('.edit-event-details-container #client-form .contact-no-container .contact-3').parent().removeClass('hide');
        }
    });
    $('.edit-event-details-container #client-form .contact-no-container .btn-remove-row').click(function() {
        $(this).parent().siblings().val('');
        $(this).parent().parent().addClass('hide');
    });
    // show estimated cost form
    $('#view-event-details-tab .new-e-v-link').click(function() {
        $('#view-event-details-tab .new-e-t-container').addClass('hide').siblings('.form-sep').remove();
        $('#view-event-details-tab .new-e-c-container').addClass('hide').siblings('.form-sep').remove();
        $('#view-event-details-tab .new-e-e-container').addClass('hide').siblings('.form-sep').remove();
        $('#view-event-details-tab .new-e-v-container').removeClass('hide')
                .after('<hr style="margin-top:0" class="form-sep">');
    });
    $('#view-event-details-tab .new-e-v-container .btn-cancel').click(function() {
        $('#view-event-details-tab .new-e-v-container').addClass('hide').siblings('.form-sep').remove();
    });
    // show event venue form
    $('#view-event-details-tab .new-e-v-link').click(function() {
        $('#view-event-details-tab .new-e-t-container').addClass('hide').siblings('.form-sep').remove();
        $('#view-event-details-tab .new-e-c-container').addClass('hide').siblings('.form-sep').remove();
        $('#view-event-details-tab .new-e-e-container').addClass('hide').siblings('.form-sep').remove();
        $('#view-event-details-tab .new-e-v-container').removeClass('hide')
                .after('<hr style="margin-top:0" class="form-sep">');
    });
    $('#view-event-details-tab .new-e-v-container .btn-cancel').click(function() {
        $('#view-event-details-tab .new-e-v-container').addClass('hide').siblings('.form-sep').remove();
    });
    // new venue
    $('.edit-event-details-container #venue-form').validate({
        rules: {
            venue_name: 'required',
            venue_address: 'required',
        },
        submitHandler: function(form) {
            var venue = {
                'venue_name': $('.edit-event-details-container #venue-form .venue-name').val(),
                'venue_address': $('.edit-event-details-container #venue-form .venue-address').val(),
                'action': $('.edit-event-details-container #venue-form #n-venue-action').val(),
            };
            save_venue(venue, $('#view-event-details-tab').attr('id'));
            return false;
        }
    });
    // show event coordinator form
    $('#view-event-details-tab .new-e-e-link').click(function() {
        $('#view-event-details-tab .new-e-t-container').addClass('hide').siblings('.form-sep').remove();
        $('#view-event-details-tab .new-e-c-container').addClass('hide').siblings('.form-sep').remove();
        $('#view-event-details-tab .new-e-v-container').addClass('hide').siblings('.form-sep').remove();
        $('#view-event-details-tab .new-e-e-container').removeClass('hide')
                .after('<hr style="margin-top:0" class="form-sep">');
    });
    $('#view-event-details-tab .new-e-e-container .btn-cancel').click(function() {
        $('#view-event-details-tab .new-e-e-container').addClass('hide').siblings('.form-sep').remove();
        $('.edit-event-details-container #emp-form .lname').val('');
        $('.edit-event-details-container #emp-form .fname').val('');
        $('.edit-event-details-container #emp-form .mname').val('');
        $('.edit-event-details-container #emp-form .bday').val('');
        $('.edit-event-details-container #emp-form .gender input[value=0]').parent().addClass('active');
        $('.edit-event-details-container #emp-form .gender input[value=1]').parent().removeClass('active');
        $('.edit-event-details-container #emp-form .date-emp').val('');
        $('.edit-event-details-container #emp-form .address-container .address-1').val('');
        $('.edit-event-details-container #emp-form .address-container .address-2').val('').parent().addClass('hide');
        $('.edit-event-details-container #emp-form .address-container .address-3').val('').parent().addClass('hide');
        $('.edit-event-details-container #emp-form .email-container .email-1').val('');
        $('.edit-event-details-container #emp-form .email-container .email-2').val('').parent().addClass('hide');
        $('.edit-event-details-container #emp-form .contact-no-container .contact-1').val('');
        $('.edit-event-details-container #emp-form .contact-no-container .contact-2').val('').parent().addClass('hide');
        $('.edit-event-details-container #emp-form .contact-no-container .contact-3').val('').parent().addClass('hide');
        $('#view-event-details-tab .new-e-e-container label.error').remove();
        $('#view-event-details-tab .new-e-e-container input.error').removeClass('error');
    });
    // new coordinator
    $('.edit-event-details-container #emp-form').validate({
        rules: {
            lname: 'required',
            fname: 'required',
            mname: 'required',
            bday: {
                required: true,
                dateISO: true,
            },
            date_emp: {
                required: true,
                dateISO: true,
            },
            address_1: 'required',
            email_1: {
                required: true,
                email: true,
            },
            email_2: 'email',
            contact_1: {
                required: true,
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
            contact_2: {
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
            contact_3: {
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
        },
        errorPlacement: function(error, element){
            var name = element.prop('name');
            if(name==='address_1'){
                $('.edit-event-details-container #emp-form .address-container .address-1').after(error);
            }else if(name==='contact_1'){
                $('.edit-event-details-container #emp-form .contact-no-container .contact-1').after(error);
            }else if(name==='contact_2'){
                $('.edit-event-details-container #emp-form .contact-no-container .contact-2').parent().after(error);
            }else if(name==='contact_3'){
                $('.edit-event-details-container #emp-form .contact-no-container .contact-3').parent().after(error);   
            }else if(name==='email_1'){
                $('.edit-event-details-container #emp-form .email-container .email-1').after(error);   
            }else if(name==='email_2'){
                $('.edit-event-details-container #emp-form .email-container .email-2').parent().after(error);   
            }else{
                error.insertAfter(element);
            }
        },
        submitHandler: function(form) {
            var address = new Array();
            var email = new Array();
            var contact = new Array();
            $('.address-container .address-text').each(function() {
                if ($(this).val() != '') {
                    address.push($(this).val());
                }
            });
            $('.edit-event-details-container #emp-form .email-container .email-text').each(function() {
                if ($(this).val() != '') {
                    email.push($(this).val());
                }
            });
            $('.edit-event-details-container #emp-form .contact-no-container .contact-no-text').each(function() {
                if ($(this).val() != '') {
                    contact.push($(this).val());
                }
            });
            var emp = {
                'lname': $('.edit-event-details-container #emp-form .lname').val(),
                'fname': $('.edit-event-details-container #emp-form .fname').val(),
                'mname': $('.edit-event-details-container #emp-form .mname').val(),
                'bday': $('.edit-event-details-container #emp-form .bday').val(),
                'gender': $('.edit-event-details-container #emp-form .gender .active input').val(),
                'date_emp': $('.edit-event-details-container #emp-form .date-emp').val(),
                'address': address.join(';'),
                'email': email.join(';'),
                'contact_no': contact.join(';'),
                'action': 0,
            };
            save_emp(emp, $('#view-event-details-tab').attr('id'));
            return false;
        }
    });
    $('.edit-event-details-container #emp-form .add-a-row').click(function() {
        if($('.edit-event-details-container #emp-form .address-container .address-1').parent().hasClass('hide')){
            $('.edit-event-details-container #emp-form .address-container .address-1').parent().removeClass('hide');
        }else if($('.edit-event-details-container #emp-form .address-container .address-2').parent().hasClass('hide')){
            $('.edit-event-details-container #emp-form .address-container .address-2').parent().removeClass('hide');
        }else if($('.edit-event-details-container #emp-form .address-container .address-3').parent().hasClass('hide')){
            $('.edit-event-details-container #emp-form .address-container .address-3').parent().removeClass('hide');
        }
    });
    $('.edit-event-details-container #emp-form .address-container .btn-remove-row').click(function() {
        $(this).parent().siblings().val('');
        $(this).parent().parent().addClass('hide');
    });
    $('.edit-event-details-container #emp-form .add-e-row').click(function() {
        if($('.edit-event-details-container #emp-form .email-container .email-1').parent().hasClass('hide')){
            $('.edit-event-details-container #emp-form .email-container .email-1').parent().removeClass('hide');
        }else if($('.edit-event-details-container #emp-form .email-container .email-2').parent().hasClass('hide')){
            $('.edit-event-details-container #emp-form .email-container .email-2').parent().removeClass('hide');
        }
    });
    $('.edit-event-details-container #emp-form .email-container .btn-remove-row').click(function() {
        $(this).parent().siblings().val('');
        $(this).parent().parent().addClass('hide');
    });
    $('.edit-event-details-container #emp-form .add-c-row').click(function() {
        if($('.edit-event-details-container #emp-form .contact-no-container .contact-1').parent().hasClass('hide')){
            $('.edit-event-details-container #emp-form .contact-no-container .contact-1').parent().removeClass('hide');
        }else if($('.edit-event-details-container #emp-form .contact-no-container .contact-2').parent().hasClass('hide')){
            $('.edit-event-details-container #emp-form .contact-no-container .contact-2').parent().removeClass('hide');
        }else if($('.edit-event-details-container #emp-form .contact-no-container .contact-3').parent().hasClass('hide')){
            $('.edit-event-details-container #emp-form .contact-no-container .contact-3').parent().removeClass('hide');
        }
    });
    $('.edit-event-details-container #emp-form .contact-no-container .btn-remove-row').click(function() {
        $(this).parent().siblings().val('');
        $(this).parent().parent().addClass('hide');
    });
    // update event details
    $('#view-event-details-tab #update-event-details-form').validate({
        rules: {
            event_name: 'required',
            event_budget: 'number',
            start_date: {
                dateISO: true,
                required: true,
            },
            end_date: {
                dateISO: true,
                required: true,
            }
        }, groups: {
            
        },
        errorPlacement: function(error, element) {
            var name = element.prop('name');
            if (name === 's_month' || name === 's_day' || name === 's_year' || name === 's_year'
                    || name === 's_hr' || name === 's_min') {
                error.insertAfter('#event-details-tab #event-details-form .start-date');
            } else if (name === 'e_month' || name === 'e_day' || name === 'e_year') {
                error.insertAfter('#event-details-tab #event-details-form .end-date');
            } else if (name === 'event_budget') {
                error.insertAfter(element.parent());
            } else {
                error.insertAfter(element);
            }
        },
        submitHandler: function(form) {
            var eventLoc = new Array();
            var eventLocName = new Array();
            $('#update-event-details-form .venue-checkbox:checked').each(function() {
                eventLoc.push($(this).val());
                eventLocName.push($(this).parent().text());
            });
            var eventDetails = {
                'event': $('#modal-event-calendar #event-id').val(),
                'event_name': $('#update-event-details-form .event-name').val(),
                'event_budget': $('#update-event-details-form .event-budget').val(),
                'event_type': $('#update-event-details-form .event-type-select option:selected').val(),
                'event_client': $('#update-event-details-form .client-select option:selected').val(),
                'event_start_date': $('#update-event-details-form .start-date').val(),
                'event_end_date': $('#update-event-details-form .end-date').val(),
                'actual_date': $('#update-event-details-form .actual-date').val() + ' ' + $('#update-event-details-form .a-hr').val() +
                        ':' + $('#update-event-details-form .a-min').val(),
                'event_loc': eventLoc.join(';'),
                'event_coord': $('#update-event-details-form .coordinator-select').val(),
                'event_note': $('#update-event-details-form .event-desc').val()
            };
            $('.loading-container').removeClass('hide');
            $.ajax({
                url: $url + 'event/event-details/update',
                type: 'post',
                data: eventDetails,
                dataType: 'json',
                success: function(data) {
                    var actualDate = eventDetails.actual_date.split(' ');
                    var date = actualDate[0].split('-');
                    var actualMonth;
                    switch (date[1]) {
                        case '01':
                            actualMonth = 'January';
                            break;
                        case '02':
                            actualMonth = 'February';
                            break;
                        case '03':
                            actualMonth = 'March';
                            break;
                        case '04':
                            actualMonth = 'April';
                            break;
                        case '05':
                            actualMonth = 'May';
                            break;
                        case '06':
                            actualMonth = 'June';
                            break;
                        case '07':
                            actualMonth = 'July';
                            break;
                        case '08':
                            actualMonth = 'August';
                            break;
                        case '09':
                            actualMonth = 'September';
                            break;
                        case '10':
                            actualMonth = 'October';
                            break;
                        case '11':
                            actualMonth = 'November';
                            break;
                        case '12':
                            actualMonth = 'December';
                            break;
                        default:
                            actualMonth = '';
                    }
                    //var time = actualDate[1].split(':');
                    if (data.status === 'success') {
                        $('#view-event-details-tab .btn-edit-event-details').html('<span class="glyphicon glyphicon-edit"></span> Edit');
                        $('#view-event-details-tab .btn-edit-event-details').addClass('btn-default');
                        $('#view-event-details-tab .btn-edit-event-details').removeClass('btn-primary');
                        $('#view-event-details-tab .view-event-details-container').removeClass('hide');
                        $('#view-event-details-tab .edit-event-details-container').addClass('hide');
                        $('#view-event-details-tab .view-event-details-container .event-name').text(eventDetails.event_name);
                        $('#view-event-details-tab .view-event-details-container .event-type').text(
                                $('#update-event-details-form .event-type-select option:selected').text());
                        $('#view-event-details-tab .view-event-details-container .event-budget').text(eventDetails.event_budget);
                        if (eventDetails.event_client === '') {
                            $('#view-event-details-tab .view-event-details-container .event-client').text('No client specified.');
                        } else {
                            $('#view-event-details-tab .view-event-details-container .event-client').text(
                                    $('#update-event-details-form .client-select option:selected').text());
                        }
                        $('#view-event-details-tab .view-event-details-container .start-date').text(eventDetails.event_start_date);
                        $('#view-event-details-tab .view-event-details-container .end-date').text(eventDetails.event_end_date);
                        $('#view-event-details-tab .view-event-details-container .actual-date').text(eventDetails.actual_date);
                        $('#view-event-details-tab .view-event-details-container .event-loc').text(eventLocName.join(';'));
                        $('#view-event-details-tab .view-event-details-container .event-coord').text(
                                $('#update-event-details-form .coordinator-select').text());
                        $('#view-event-details-tab .view-event-details-container .event-notes').text(eventDetails.event_note);
                        $('#view-event-details-tab .view-event-details-container .a-d-yr').text(date[0]);
                        $('#view-event-details-tab .view-event-details-container .a-d-day').text(date[2]);
                        $('#view-event-details-tab .view-event-details-container .a-d-month').text(actualMonth);
                        $('#view-event-details-tab .alert').remove();
                        $('#view-event-details-tab .new-e-t-container').addClass('hide').siblings('.form-sep').remove();
                        $('#view-event-details-tab hr').after('<div class="alert alert-success margin-top">' + data.msg + '</div>');
                        $('#update-event-details-form .all-venues').addClass('hide');
                        $('#update-event-details-form .venue-select .default-venue').prop('selected', true);
                        remove_alert();
                        $('.loading-container').addClass('hide');
                    } else {
                        $('#view-event-details-tab .alert').remove();
                        $('#view-event-details-tab .new-e-t-container').addClass('hide').siblings('.form-sep').remove();
                        $('#view-event-details-tab hr').after('<div class="alert alert-warning margin-top">' + data.msg + '</div>');
                        remove_alert();
                        $('.loading-container').addClass('hide');
                    }
                },
                error: function(xhr, status) {
                    $('.loading-container').addClass('hide');
                }
            });
            $('#update-event-details-form input.error').removeClass('error');
            $('#update-event-details-form label.error').remove();
            return false;
        }
    });
    // assigning event supplier
    $('#view-event-supplier-tab #assign-e-s-form').validate({
        errorPlacement: function(error, element) {
            var name = element.prop('name');
            if (name === 'event_supplier') {
                $('#view-event-supplier-tab label[class=error]').remove();
                error.insertAfter(element.parent().parent());
            }
        },
        submitHandler: function(form) {
            var supplier = $('#view-event-supplier-tab select[name=event_supplier] option:selected').text();
            var existing;
            $('#view-event-supplier-tab .assigned-event-supplier-container .list-group').each(function() {
                if ($(this).children().children().children('.company-name').text() === supplier) {
                    existing = true;
                    return false;
                }
            });
            if (existing) {
                $('#view-event-supplier-tab').prepend('<div class="alert alert-danger margin-top">Supplier already assigned.</div>');
                error_msg();
            } else {
                $('.loading-container').removeClass('hide');
                $.ajax({
                    url: $url + 'event/supplier/get',
                    type: 'post',
                    data: {'supplier_id': $('#view-event-supplier-tab select[name=event_supplier] option:selected').val()},
                    dataType: 'json',
                    success: function(data) {
                        if (data.status === 'success') {
                            $('#view-event-supplier-tab .assigned-event-supplier-container').
                                    prepend('<div class="list-group" style="padding:1%;border: solid 1px #cccccc;position:relative;">' +
                                    '<div class="view-supplier-services hide"><div class="panel"><div class="panel-body"></div></div><div class="pull-right">' +
                                    '<button type="button" class="btn btn-default btn-cancel">Cancel</button> ' +
                                    '<button type="button" class="btn btn-primary btn-assign">Assign</button>' +
                                    '</div>' +
                                    '<div class="clearfix"></div></div>' +
                                    '<div class="e-s-container">' +
                                    '<h4 class="list-group-item-heading">Company Name: <span class="company-name">' + data.supplier.company + '</span></h4>' +
                                    '<p class="list-group-item-text">Contact Person: ' + data.supplier.contact_person + '</p>' +
                                    '<p class="list-group-item-text">Contact No.: ' + data.supplier.s_num + '</p>' +
                                    '<p class="list-group-item-text">Available Services: <span class="available-services">' + data.supplier.services + '</span></p>' +
                                    '<p class="list-group-item-text">Services chosen: <span class="services-chosen"></span></p>' +
                                    '<div class="btn-group pull-right">' +
                                    '<a href="#services-popup" data-toggle="modal" class="btn-assign-services" data-supplierid="' + data.supplier.supplier_id + '">Services</a>' +
                                    '</div><div class="clearfix"></div></div></div>');
                            $('.loading-container').addClass('hide');
                        } else {
                            $('#view-event-supplier-tab .alert-success').remove();
                            $('#view-event-supplier-tab .alert-danger').remove();
                            $('#view-event-supplier-tab').prepend('<div class="alert alert-error">">Something went wrong while getting the supplier.<br/>Please try again.</div>');
                            $('.loading-container').addClass('hide');
                        }
                        $('#view-event-supplier-tab #assign-e-s-form .exsiting-supplier option[class=default-value]')
                                .prop('selected', true);
                    },
                    error: function(xhr, status) {
                        $('.loading-container').addClass('hide');
                    }
                });
            }
            return false;
        }
    });
    // assign supplier services
    $('#view-event-supplier-tab .assigned-event-supplier-container').on('click', '.list-group .btn-assign-services', function() {
        $(this).parent().parent().addClass('hide');
        var $chosenServices = $(this).parent().siblings().children('.services-chosen').text();
        var $current = $(this);
        $current.parent().parent().siblings('.view-supplier-services').removeClass('hide');
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'event/get/services',
            type: 'post',
            data: {'supplier_id': $(this).attr('data-supplierid')},
            dataType: 'json',
            success: function(data) {
                var services = data.services.split(';');
                //var chosen = $chosenServices.split(';');
                $current.parent().parent().siblings('.view-supplier-services').children().children('.panel-body').empty();
                if (!$current.parent().parent().siblings('.view-supplier-services').children().hasClass('services-form')) {
                    $current.parent().parent().siblings('.view-supplier-services').
                            prepend('<div class="services-form row">' +
                            '<input type="hidden" class="supplier-id" value="' + data.supplier_id + '" />' +
                            '<div class="input-group col-md-6">' +
                            '<input type="text" class="form-control service-name required" name="service_name" placeholder="New Services...">' +
                            '<span class="input-group-btn">' +
                            '<button class="btn btn-default btn-new-service" title="Add new service"><span class="glyphicon glyphicon-plus"></span></button>' +
                            '</span>' +
                            '</div>' +
                            '</div>');
                }

                for (var i = 0; i < services.length; i++) {
//                    for(var x=0;x<chosen.length;x++){
                    if ($chosenServices.indexOf(services[i]) > -1) {
                        $current.parent().parent().siblings('.view-supplier-services').children().children('.panel-body').
                                append('<label><input type="checkbox" class="services-checkbox" checked="checked" /> ' + services[i] + '</label>&nbsp;&nbsp;');
//                            break;
                    } else {
                        $current.parent().parent().siblings('.view-supplier-services').children().children('.panel-body').
                                append('<label><input type="checkbox" class="services-checkbox" /> ' + services[i] + '</label>&nbsp;&nbsp;');
                    }
                }
                $('.loading-container').addClass('hide');
            },
            error: function(xhr, status) {
                $('.loading-container').addClass('hide');
            }
        });
    });
    // 
    $('#view-event-supplier-tab').on('click', '.view-supplier-services .btn-cancel', function() {
        $(this).parent().parent().addClass('hide');
        $(this).parent().parent().siblings().removeClass('hide');
    });
    //  services
    $('#view-event-supplier-tab').on('click', '.view-supplier-services .btn-assign', function() {
        var $supplier_id = $(this).parent().parent().siblings().children().children('.btn-assign-services').attr('data-supplierid');
        var $checked = $('#view-event-supplier-tab .view-supplier-services .panel-body .services-checkbox:checked').size();
        var pick = new Array();
        var $current = $(this);
        $('#view-event-supplier-tab .view-supplier-services .panel-body .services-checkbox:checked').each(function() {
            pick.push($(this).parent().text());
        });
        if ($(this).parent().parent().siblings().children().children('a').hasClass('unassign-supplier')) {
            $('.loading-container').removeClass('hide');
            $.ajax({
                url: $url + 'event/sup-services/update',
                type: 'post',
                data: {
                    'event': $('#modal-event-calendar #event-id').val(),
                    'supplier_id': $supplier_id,
                    'services': pick.join(';'),
                },
                dataType: 'json',
                success: function(data) {
                    if (data.status === 'success') {
                        if ($checked > 0) {
                            $current.parent().parent().parent().css('background-color', '#99ff99').
                                    children().children().children('.services-chosen').text(pick.join(';'));
                            if (!$current.parent().parent().siblings().children().children('.unassign-supplier').hasClass('unassign-supplier')) {
                                $current.parent().parent().siblings().children('.btn-group')
                                        .append('<span class="separator"> | </span><a class="unassign-supplier">Unasign supplier</a>');
                            }
                            $current.parent().parent().addClass('hide');
                            $current.parent().parent().siblings().removeClass('hide');
                        } else {
                            $current.parent().parent().parent().
                                    children().children().children('.services-chosen').text('');
                            $current.parent().parent().addClass('hide');
                            $current.parent().parent().siblings().removeClass('hide');
                        }
                        $('#view-event-supplier-tab').prepend('<div class="alert alert-success margin-top">' + data.msg + '</div>');
                        success_msg();
                        $('.loading-container').addClass('hide');
                    } else {
                        $current.parent().parent().addClass('hide');
                        $current.parent().parent().siblings().removeClass('hide');
                        $('#view-event-supplier-tab').prepend('<div class="alert alert-danger margin-top">' + data.msg + '</div>');
                        error_msg();
                        $('.loading-container').addClass('hide');
                    }
                    pick = [];
                },
                error: function(xhr, status) {
                    $('.loading-container').addClass('hide');
                }
            });
        } else {
            $('.loading-container').removeClass('hide');
            $.ajax({
                url: $url + 'event/add-supplier',
                type: 'post',
                data: {
                    'event': $('#modal-event-calendar #event-id').val(),
                    'supplier_id': $supplier_id,
                    'services': pick.join(';'),
                },
                dataType: 'json',
                success: function(data) {
                    if (data.status === 'success') {
                        if ($checked > 0) {
                            $current.parent().parent().parent().css('background-color', '#99ff99').
                                    children().children().children('.services-chosen').text(pick.join(';'));
                            if (!$current.parent().parent().siblings().children().children('.unassign-supplier').hasClass('unassign-supplier')) {
                                $current.parent().parent().siblings().children('.btn-group')
                                        .append('<span class="separator"> | </span><a class="unassign-supplier">Unasign supplier</a>');
                            }
                            $current.parent().parent().addClass('hide');
                            $current.parent().parent().siblings().removeClass('hide');
                        } else {
                            $current.parent().parent().parent().css('background-color', '#99ff99').
                                    children().children().children('services-chosen').text('');
                            $current.parent().parent().siblings().children('.btn-group')
                                    .append('<span class="separator"> | </span><a class="unassign-supplier">Unasign supplier</a>');
                            $current.parent().parent().addClass('hide');
                            $current.parent().parent().siblings().removeClass('hide');
                        }
                        $('#view-event-supplier-tab').prepend('<div class="alert alert-success margin-top">' + data.msg + '</div>');
                        success_msg();
                        $('.loading-container').addClass('hide');
                    } else {
                        $current.parent().parent().addClass('hide');
                        $current.parent().parent().siblings().removeClass('hide');
                        $('#view-event-supplier-tab').prepend('<div class="alert alert-danger margin-top">' + data.msg + '</div>');
                        error_msg();
                        $('.loading-container').addClass('hide');
                    }
                    pick = [];
                },
                error: function(xhr, status) {
                    $('.loading-container').addClass('hide');
                }
            });
        }
    });
    // add services
    $('#view-event-supplier-tab').on('click', '.view-supplier-services .services-form .btn-new-service', function() {
        var $current = $(this);
        if ($(this).parent().siblings().val() !== '') {
            $(this).parent().parent().parent().siblings('.required-error').remove();
            var service = {
                'service': $(this).parent().siblings('.service-name').val(),
                'supplier_id': $(this).parent().parent().siblings('.supplier-id').val(),
            };
            var data = new Array();
            $(this).parent().parent().parent().siblings('.panel').children().children().children('.services-checkbox').each(function() {
                data.push($(this).parent().text().replace(/\s+/g, ''));
            });
            if ($.inArray(service.service, data) == -1) {
                $('.loading-container').removeClass('hide');
                $.ajax({
                    url: $url + 'event/save/service',
                    type: 'post',
                    data: service,
                    dataType: 'json',
                    success: function(data) {
                        var $available_services = $current.parent().parent().parent().parent().siblings().children().children('.available-services').text();
                        if (data.status == 'success') {
                            $current.parent().parent().parent().parent().children('.alert').remove();
                            $current.parent().parent().parent().siblings().children('.panel-body').
                                    prepend('<label><input type="checkbox" class="services-checkbox" /> ' + service.service + '</label>&nbsp;&nbsp;');
                            $current.parent().parent().parent().parent().siblings().children().children('.available-services').text($available_services + ';' +
                                    $current.parent().siblings('.service-name').val());
                            $current.parent().siblings('.service-name').val('');
                            $current.parent().parent().parent().parent().prepend('<div class="alert alert-success">' + data.msg + '</div>');
                            success_msg();
                            $('.loading-container').addClass('hide');
                        } else {
                            $current.parent().parent().parent().parent().children('.alert').remove();
                            $current.parent().parent().parent().parent().prepend('<div class="alert alert-danger">' + data.msg + '</div>');
                            error_msg();
                            $('.loading-container').addClass('hide');
                        }
                    },
                    error: function() {
                        $current.parent().parent().parent().parent().children('.alert').remove();
                        $(this).parent().parent().parent().parent().prepend('<div class="alert alert-danger">Something went wrong while saving the service. Please try again later.</div>');
                        error_msg();
                        $('.loading-container').addClass('hide');
                    }
                });
            } else {
                $current.parent().parent().parent().parent().children('.alert').remove();
                $(this).parent().parent().parent().parent().prepend('<div class="alert alert-danger">Service already exist.</div>');
                error_msg();
            }
        } else {
            if (!$(this).parent().parent().parent().siblings('label').hasClass('required-error')) {
                $(this).parent().parent().parent().after('<label class="required-error">This field is required.</label>');
            }
        }
    });
    // unassign supplier
    $('#view-event-supplier-tab').on('click', '.e-s-container .unassign-supplier', function() {
        var $current = $(this);
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'event/remove-supplier',
            type: 'post',
            data: {'supplier_id': $(this).siblings().attr('data-supplierid')},
            dataType: 'json',
            success: function(data) {
                if (data.status === 'success') {
                    $('#view-event-supplier-tab .alert-success').remove();
                    $('#view-event-supplier-tab .alert-danger').remove();
                    $('#view-event-supplier-tab').prepend('<div class="alert alert-success">' + data.msg + '</div>');
                    success_msg();
                    $current.parent().parent().parent().remove();
                    $('.loading-container').addClass('hide');
                } else {
                    $('#view-event-supplier-tab .alert-success').remove();
                    $('#view-event-supplier-tab .alert-danger').remove();
                    $('#view-event-supplier-tab').prepend('<div class="alert alert-danger">' + data.msg + '</div>');
                    error_msg();
                    $('.loading-container').addClass('hide');
                }
            },
            error: function() {
                $('#view-event-supplier-tab .alert-success').remove();
                $('#view-event-supplier-tab .alert-danger').remove();
                $('#view-event-supplier-tab').prepend('<div class="alert alert-danger">Something went while removing supplier from the event.<br/>Please try again.</div>');
                error_msg();
                $('.loading-container').addClass('hide');
            }
        });
    });
    // update event checklist
    $('#view-event-checklist-tab').on('click', '.btn-update', function() {
        var checklist_id = new Array();
        $('#view-event-checklist-tab .checklist-checkbox').each(function() {
            if ($(this).is(':checked')) {
                checklist_id.push($(this).val() + '-' + '1' + '-' + $(this).parent().siblings().children('.checklist-remarks').val());
            } else {
                checklist_id.push($(this).val() + '-' + '0' + '-' + $(this).parent().siblings().children('.checklist-remarks').val());
            }
        });
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'event/event-checklist/update',
            type: 'post',
            data: {
                'event': $('#modal-event-calendar #event-id').val(),
                'checklist': checklist_id,
            },
            dataType: 'json',
            success: function(data) {
                if (data.status === 'success') {
                    $('#view-event-checklist-tab .alert').remove();
                    $('#view-event-checklist-tab').prepend('<div class="alert alert-success margin-top">' + data.msg + '</div>');
                    success_msg();
                    $('.loading-container').addClass('hide');
                } else {
                    $('#view-event-checklist-tab .alert').remove();
                    $('#view-event-checklist-tab').prepend('<div class="alert alert-danger margin-top">' + data.msg + '</div>');
                    error_msg();
                    $('.loading-container').addClass('hide');
                }
            },
            error: function(xhr, status) {
                $('.loading-container').addClass('hide');
            }
        });
    });
    $('#view-event-checklist-tab .btn-new-checklist-item').click(function() {
        $(this).addClass('hide');
        $('#view-event-checklist-tab .checklist-panel').removeClass('hide');
    });
    $('#view-event-checklist-tab #new-checklist-item-form .category-select').change(function() {
        if ($('#view-event-checklist-tab #new-checklist-item-form .category-select option:selected').text() === 'Category') {
            $('#view-event-checklist-tab #new-checklist-item-form .checklist-item-container').addClass('hide');
            $('#view-event-checklist-tab #new-checklist-item-form .checklist-select .default-val').prop('selected', true);
            $('#view-event-checklist-tab #new-checklist-item-form .btn-save').prop('disabled', true);
            $('#view-event-checklist-tab #new-checklist-item-form select.error').removeClass('error');
            $('#view-event-checklist-tab #new-checklist-item-form label.error').remove();
        } else {
            var $cat_id = $('#view-event-checklist-tab #new-checklist-item-form .category-select option:selected').val();
            $('.loading-container').removeClass('hide');
            $.ajax({
                url: $url + 'event/event-checklist/get-checklist-item',
                type: 'post',
                data: {'category_id': $cat_id},
                dataType: 'json',
                success: function(checklist) {
                    $('#view-event-checklist-tab #new-checklist-item-form .checklist-item-container .default-val')
                            .siblings().empty();
                    $.each(checklist, function(key, value) {
                        $('#view-event-checklist-tab #new-checklist-item-form .checklist-select .default-val')
                                .after('<option value="' + value.checklist_id + '">' + value.list_description + '</option>');
                    });
                    $('.loading-container').addClass('hide');
                },
                error: function(xhr, status) {
                    $('.loading-container').addClass('hide');
                }
            });
            $('#view-event-checklist-tab #new-checklist-item-form .checklist-item-container').removeClass('hide');
            $('#view-event-checklist-tab #new-checklist-item-form .btn-save').prop('disabled', false);
            $('#view-event-checklist-tab #new-checklist-item-form .checklist-select .default-val').prop('selected', true);
            $('#view-event-checklist-tab #new-checklist-item-form select.error').removeClass('error');
            $('#view-event-checklist-tab #new-checklist-item-form label.error').remove();
        }
    });
    $('#view-event-checklist-tab #new-checklist-item-form .btn-cancel').click(function() {
        $('#view-event-checklist-tab #new-checklist-item-form .category-select .default-val').prop('selected', true);
        $('#view-event-checklist-tab #new-checklist-item-form .checklist-select .default-val').prop('selected', true);
        $('#view-event-checklist-tab #new-checklist-item-form .checklist-item-container').addClass('hide');
        $('#view-event-checklist-tab .checklist-panel').addClass('hide');
        $('#view-event-checklist-tab .btn-new-checklist-item').removeClass('hide');
        $('#view-event-checklist-tab #new-checklist-item-form select.error').removeClass('error');
        $('#view-event-checklist-tab #new-checklist-item-form label.error').remove();
    });
    $('#view-event-checklist-tab #new-checklist-item-form').validate({
        submitHandler: function(form) {
            var $checklistId = $('#view-event-checklist-tab #new-checklist-item-form .checklist-select option:selected').val();
            var $checklistText = $('#view-event-checklist-tab #new-checklist-item-form .checklist-select option:selected').text();
            $('.loading-container').removeClass('hide');
            $.ajax({
                url: $url + 'event/checklist/save',
                type: 'post',
                data: {'event': $('#modal-event-calendar #event-id').val(), 'checklist_id': $checklistId},
                dataType: 'json',
                success: function(data) {
                    if (data.status === 'success') {
                        $('#view-event-checklist-tab .checklist-list tbody').prepend('<tr>' +
                                '<td>' + $checklistText + '</td>' +
                                '<td><input type="checkbox" name="checklist_status" class="checklist-checkbox" value="' + $checklistId + '" /></td>' +
                                '<td><textarea class="checklist-remarks" style="width:100%"></textarea></td>' +
                                '</tr>');
                        $('#view-event-checklist-tab #new-checklist-item-form .checklist-item-container').addClass('hide');
                        $('#view-event-checklist-tab #new-checklist-item-form .checklist-select .default-val').prop('selected', true);
                        $('#view-event-checklist-tab #new-checklist-item-form .checklist-select .default-val').prop('selected', true);
                        $('#view-event-checklist-tab #new-checklist-item-form .checklist-item-container').addClass('hide');
                        $('#view-event-checklist-tab #new-checklist-item-form .btn-save').prop('disabled', true);
                        $('#view-event-checklist-tab #new-checklist-item-form select.error').removeClass('error');
                        $('#view-event-checklist-tab #new-checklist-item-form label.error').remove();
                        $('#view-event-checklist-tab .alert').remove();
                        $('#view-event-checklist-tab').prepend('<div class="alert alert-success">' + data.msg + '</div>');
                        success_msg();
                        $('.loading-container').addClass('hide');
                    } else {
                        $('#view-event-checklist-tab #new-checklist-item-form .checklist-item-container').addClass('hide');
                        $('#view-event-checklist-tab #new-checklist-item-form .checklist-select .default-val').prop('selected', true);
                        $('#view-event-checklist-tab #new-checklist-item-form .checklist-select .default-val').prop('selected', true);
                        $('#view-event-checklist-tab #new-checklist-item-form .checklist-item-container').addClass('hide');
                        $('#view-event-checklist-tab #new-checklist-item-form .btn-save').prop('disabled', true);
                        $('#view-event-checklist-tab #new-checklist-item-form select.error').removeClass('error');
                        $('#view-event-checklist-tab #new-checklist-item-form label.error').remove();
                        $('#view-event-checklist-tab .alert').remove();
                        $('#view-event-checklist-tab').prepend('<div class="alert alert-danger">' + data.msg + '</div>');
                        error_msg();
                        $('.loading-container').addClass('hide');
                    }
                },
                error: function(xhr, status) {
                    $('.loading-container').addClass('hide');
                }
            });
            return false;
        }
    });
    // task 
    $('#view-task-tab .btn-new-task').click(function() {
        $(this).addClass('hide');
        $('#view-task-tab .task-container').removeClass('hide');
    });
    $('#view-task-tab #task-form .btn-cancel').click(function() {
        $('#view-task-tab .task-container').addClass('hide');
        $('#view-task-tab .btn-new-task').removeClass('hide');
    });
    $('#view-task-tab #task-form').validate({
        rules: {
            task_desc: 'required'
        },
        groups: {
            bday: 'task_month task_day task_year task_hr task_min'
        },
        errorPlacement: function(error, element) {
            var name = element.prop('name');
            if (name === 'task_month' || name === 'task_day' || name === 'task_year' || name === 'task_hr' ||
                    name === 'task_min') {
                error.appendTo($('#view-task-tab #task-form .date-time'));
            } else {
                error.insertAfter(element);
            }
        },
        submitHandler: function(form) {
            var task = {
                'task_desc': $('#view-task-tab #task-form .task-desc').val(),
                'task_date': $('#view-task-tab #task-form .task-date').val(),
                'task_time': $('#view-task-tab #task-form .task-hr option:selected').text() + ':' +
                        $('#view-task-tab #task-form .task-min option:selected').text() + ':00',
            };
            $('.loading-container').removeClass('hide');
            $.ajax({
                url: $url + 'event/task/save',
                type: 'post',
                data: task,
                dataType: 'json',
                success: function(data) {
                    if (data.status === 'success') {
                        $('#view-task-tab #task-list').
                                prepend('<div class="list-group col-md-6" style="padding:1em;border: solid 1px #cccccc;" data-taskid="' + data.task + '">' +
                                '<p class="list-group-item-text">Task: <span class="task-desc">' + task.task_desc + '</span></p>' +
                                '<p class="list-group-item-text">Date and Time: <span class="task-date"> ' + task.task_date +
                                '</span> <span class="task-time">' + task.task_time + '</span></p>' +
                                '<div class="btn-group pull-right">' +
                                '<a class="btn-remove-task" data-taskid="' + data.task + '">Remove task</a>' +
                                '</div><div class="clearfix"></div></div>');
                        $('#view-task-tab #task-form .task-desc').val('');
                        $('#view-task-tab #task-form .task-date').val('');
                        $('#view-task-tab #task-form .task-hr option[value=""]').prop('selected', true);
                        $('#view-task-tab #task-form .task-min option[value=""]').prop('selected', true);
                        $('#view-task-tab .alert').remove();
                        $('#view-task-tab').prepend('<div class="alert alert-success">' + data.msg + '</div>');
                        success_msg();
                        $('.loading-container').addClass('hide');
                    } else {
                        $('#view-task-tab .alert').remove();
                        $('#view-task-tab').prepend('<div class="alert alert-success">' + data.msg + '</div>');
                        success_msg();
                        $('.loading-container').addClass('hide');
                    }
                },
                error: function(xhr, status) {
                    $('.loading-container').addClass('hide');
                }
            });
            return false;
        }
    });
    $('#view-task-tab').on('click', '#task-list .list-group .btn-remove-task', function() {
        var $taskId = $(this).attr('data-taskid');
        var $current = $(this);
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'event/task/delete',
            type: 'post',
            data: {'task_id': $taskId},
            dataType: 'json',
            success: function(data) {
                if (data.status === 'success') {
                    $current.parent().parent().remove();
                    $('#view-task-tab .alert').remove();
                    $('#view-task-tab').prepend('<div class="alert alert-success">' + data.msg + '</div>');
                    success_msg();
                    if($('#view-task-tab #task-list').children().length===0){
                        $('#view-task-tab #task-list').append('<div class="alert alert-info">You dont have anymore task to do. :D</div>');
                    }
                    $('.loading-container').addClass('hide');
                } else {
                    $('#view-task-tab .alert').remove();
                    $('#view-task-tab').prepend('<div class="alert alert-danger">' + data.msg + '</div>');
                    error_msg();
                    $('.loading-container').addClass('hide');
                }
            },
            error: function(xhr, status) {
                $('.loading-container').addClass('hide');
            }
        });
    });
    // Create Event-------------------------------------------------------------
    // Event Details
    $('#event-details-form .start-date').datepicker({
        autoclose: true,
        format: "yyyy-mm-dd",
        todayHighlight: true,
    });
    $('#event-details-form .end-date').datepicker({
        autoclose: true,
        format: "yyyy-mm-dd",
        todayHighlight: true,
    });
    $('#event-details-form .actual-date').datepicker({
        autoclose: true,
        format: "yyyy-mm-dd",
        todayHighlight: true,
    });
    // new event type
    $('#e-d-new-event-type-popup #event-type-form').validate({
        rules: {
            event_type_name: 'required',
        },
        submitHandler: function(form) {
            $('.loading-container').removeClass('hide');
            $.ajax({
                url: $url + 'event-type/save',
                type: 'POST',
                dataType: 'json',
                data: {'event_type_name': $('#e-d-new-event-type-popup .event-type-name').val()},
                success: function(data) {
                    if (data.status === 'success') {
                        $('#e-d-new-event-type-popup .event-type-name').val('');
                        $('.alert-success').remove();
                        $('.alert-danger').remove();
                        $('#event-details-tab .event-type-select').append('<option value="' + data.type.type_id + '">' + data.type.type_name + '</option>');
                        $('.create-event-container').prepend('<div class="alert alert-success margin-top">' + data.msg + '</div>');
                        $('#e-d-new-event-type-popup').modal('hide');
                        success_msg();
                        $('.loading-container').addClass('hide');
                    } else {
                        if (data.type == 'already exist') {
                            $('.alert-success').remove();
                            $('.alert-danger').remove();
                            $('#e-d-new-event-type-popup #event-type-form').before('<div class="alert alert-danger">' + data.msg + '</div>');
                            error_msg();
                        } else {
                            $('#e-d-new-event-type-popup .event-type-name').val('');
                            $('.alert-success').remove();
                            $('.alert-danger').remove();
                            $('.create-event-container').prepend('<div class="alert alert-danger margin-top">' + data.msg + '</div>');
                            $('#e-d-new-event-type-popup').modal('hide');
                            error_msg();
                        }
                        $('.loading-container').addClass('hide');
                    }
                },
                error: function() {
                    $('#e-d-new-event-type-popup .event-type-name').val('');
                    $('.alert-success').remove();
                    $('.alert-danger').remove();
                    $('.create-event-container').prepend('<div class="alert alert-danger margin-top">Something went wrong while saving the event type. Please try again later.</div>');
                    $('#e-d-new-event-type-popup').modal('hide');
                    error_msg();
                    $('.loading-container').addClass('hide');
                }
            });
            return false;
        }
    });
    $('#e-d-new-event-type-popup').on('hide.bs.modal', function() {
        $('#e-d-new-event-type-popup .event-type-name').val('');
        $('#e-d-new-event-type-popup input.error').removeClass('error');
        $('#e-d-new-event-type-popup label.error').remove();
    });
    // new client
    $('#e-d-new-client-popup #client-form').validate({
        rules: {
            lname: 'required',
            fname: 'required',
            address_1: 'required',
            email_1: {
                required: true,
                email: true,
            },
            email_2: {
                email: true,
            },
            contact_1: {
                required: true,
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
            contact_2: {
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
            contact_3: {
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
        },
        submitHandler: function(form) {
            var address = new Array();
            var email = new Array();
            var contact = new Array();
            $('#e-d-new-client-popup .address-container .address-text').each(function() {
                if ($(this).val() != '') {
                    address.push($(this).val());
                }
            });
            $('#e-d-new-client-popup .email-container .email-text').each(function() {
                if ($(this).val() != '') {
                    email.push($(this).val());
                }
            });
            $('#e-d-new-client-popup .contact-no-container .contact-no-text').each(function() {
                if ($(this).val() != '') {
                    contact.push($(this).val());
                }
            });
            var client = {
                'lname': $('#e-d-new-client-popup .lname').val(),
                'fname': $('#e-d-new-client-popup .fname').val(),
                'address': address.join(';'),
                'email': email.join(';'),
                'contact_no': contact.join(';'),
                'action': 0,
            };
            save_client(client, $('#e-d-new-client-popup').attr('id'));
            return false;
        }
    });
    $('#e-d-new-client-popup').on('hide.bs.modal', function() {
        $('#e-d-new-client-popup input.error').removeClass('error');
        $('#e-d-new-client-popup label.error').remove();
        $('#e-d-new-client-popup .lname').val('');
        $('#e-d-new-client-popup .fname').val('');
        $('#e-d-new-client-popup .address-container .address-1').val('').parent().addClass('hide');
        $('#e-d-new-client-popup .address-container .address-2').val('').parent().addClass('hide');
        $('#e-d-new-client-popup .address-container .address-3').val('').parent().addClass('hide');
        $('#e-d-new-client-popup .email-container .email-1').val('').parent().addClass('hide');
        $('#e-d-new-client-popup .email-container .email-2').val('').parent().addClass('hide');
        $('#e-d-new-client-popup .contact-no-container .contact-1').val('').parent().addClass('hide');
        $('#e-d-new-client-popup .contact-no-container .contact-2').val('').parent().addClass('hide');
        $('#e-d-new-client-popup .contact-no-container .contact-3').val('').parent().addClass('hide');
    });
    $('#e-d-new-client-popup .add-a-row').click(function() {
        if($('#e-d-new-client-popup .address-container .address-1').parent().hasClass('hide')){
            $('#e-d-new-client-popup .address-container .address-1').parent().removeClass('hide');
        }else if($('#e-d-new-client-popup .address-container .address-2').parent().hasClass('hide')){
            $('#e-d-new-client-popup .address-container .address-2').parent().removeClass('hide');
        }else if($('#e-d-new-client-popup .address-container .address-3').parent().hasClass('hide')){
            $('#e-d-new-client-popup .address-container .address-3').parent().removeClass('hide');
        }
    });
    $('#e-d-new-client-popup .address-container .btn-remove-row').click(function() {
        $(this).parent().siblings().val('');
        $(this).parent().parent().addClass('hide');
    });
    $('#e-d-new-client-popup .add-e-row').click(function() {
        if($('#e-d-new-client-popup .email-container .email-1').parent().hasClass('hide')){
            $('#e-d-new-client-popup .email-container .email-1').parent().removeClass('hide');
        }else if($('#e-d-new-client-popup .email-container .email-2').parent().hasClass('hide')){
            $('#e-d-new-client-popup .email-container .email-2').parent().removeClass('hide');
        }
    });
    $('#e-d-new-client-popup .email-container .btn-remove-row').click(function() {
        $(this).parent().siblings().val('');
        $(this).parent().parent().addClass('hide');
    });
    $('#e-d-new-client-popup .add-c-row').click(function() {
        if($('#e-d-new-client-popup .contact-no-container .contact-1').parent().hasClass('hide')){
            $('#e-d-new-client-popup .contact-no-container .contact-1').parent().removeClass('hide');
        }else if($('#e-d-new-client-popup .contact-no-container .contact-2').parent().hasClass('hide')){
            $('#e-d-new-client-popup .contact-no-container .contact-2').parent().removeClass('hide');
        }else if($('#e-d-new-client-popup .contact-no-container .contact-3').parent().hasClass('hide')){
            $('#e-d-new-client-popup .contact-no-container .contact-3').parent().removeClass('hide');
        }
    });
    $('#e-d-new-client-popup .contact-no-container .btn-remove-row').click(function() {
        $(this).parent().siblings().val('');
        $(this).parent().parent().addClass('hide');
    });
    // new venue
    $('#e-d-new-venue-popup #venue-form').validate({
        rules: {
            venue_name: 'required',
            venue_address: 'required',
        },
        submitHandler: function(form) {
            var venue = {
                'venue_name': $('#e-d-new-venue-popup .venue-name').val(),
                'venue_address': $('#e-d-new-venue-popup .venue-address').val(),
                'action': $('#e-d-new-venue-popup #n-venue-action').val(),
            };
            save_venue(venue, $('#e-d-new-venue-popup').attr('id'));
            return false;
        }
    });
    $('#e-d-new-venue-popup').on('hide.bs.modal', function() {
        $('#e-d-new-venue-popup input.error').removeClass('error');
        $('#e-d-new-venue-popup label.error').remove();
        $('#e-d-new-venue-popup .venue-name').val('');
        $('#e-d-new-venue-popup .venue-address').val('');
    });
    // new coordinator
    $('#e-d-new-coord-popup #emp-form').validate({
        rules: {
            lname: 'required',
            fname: 'required',
            mname: 'required',
            date_emp: {
                required: true,
                dateISO: true,
            },
            bday: {
                required: true,
                dateISO: true,
            },
            address_1: 'required',
            email_1: {
                required: true,
                email: true,
            },
            email_2: 'email',
            contact_1: {
                required: true,
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
            contact_2: {
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
            contact_3: {
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
        },
        errorPlacement: function(error, element){
            var name = element.prop('name');
            if(name==='address_1'){
                $('#e-d-new-coord-popup .address-container .address-1').after(error);
            }else if(name==='contact_1'){
                $('#e-d-new-coord-popup .contact-no-container .contact-1').after(error);
            }else if(name==='contact_2'){
                $('#e-d-new-coord-popup .contact-no-container .contact-2').parent().after(error);
            }else if(name==='contact_3'){
                $('#e-d-new-coord-popup .contact-no-container .contact-3').parent().after(error);   
            }else if(name==='email_1'){
                $('#e-d-new-coord-popup .email-container .email-1').after(error);   
            }else if(name==='email_2'){
                $('#e-d-new-coord-popup .email-container .email-2').parent().after(error);   
            }else{
                error.insertAfter(element);
            }
        },
        submitHandler: function(form) {
            var address = new Array();
            var email = new Array();
            var contact = new Array();
            $('#e-d-new-coord-popup .address-container .address-text').each(function() {
                if ($(this).val() != '') {
                    address.push($(this).val());
                }
            });
            $('#e-d-new-coord-popup .email-container .email-text').each(function() {
                if ($(this).val() != '') {
                    email.push($(this).val());
                }
            });
            $('#e-d-new-coord-popup .contact-no-container .contact-no-text').each(function() {
                if ($(this).val() != '') {
                    contact.push($(this).val());
                }
            });
            var emp = {
                'lname': $('#e-d-new-coord-popup .lname').val(),
                'fname': $('#e-d-new-coord-popup .fname').val(),
                'mname': $('#e-d-new-coord-popup .mname').val(),
                'bday': $('#e-d-new-coord-popup .bday').val(),
                'gender': $('#e-d-new-coord-popup .gender .active input').val(),
                'date_emp': $('#e-d-new-coord-popup .date-emp').val(),
                'address': address.join(';'),
                'email': email.join(';'),
                'contact_no': contact.join(';'),
                'action': 0,
            };
            save_emp(emp, $('#e-d-new-coord-popup').attr('id'));
            return false;
        }
    });
//    $('#e-d-new-coord-popup .bday').datepicker({
//        autoclose: true,
//        format: "yyyy-mm-dd",
//        todayHighlight: true,
//    });
//    $('#e-d-new-coord-popup .date-emp').datepicker({
//        autoclose: true,
//        format: "yyyy-mm-dd",
//        todayHighlight: true,
//    });
    $('#e-d-new-coord-popup').on('hide.bs.modal', function() {
        $('#e-d-new-coord-popup select.error').removeClass('error');
        $('#e-d-new-coord-popup input.error').removeClass('error');
        $('#e-d-new-coord-popup label.error').remove();
        $('#e-d-new-coord-popup .lname').val('');
        $('#e-d-new-coord-popup .fname').val('');
        $('#e-d-new-coord-popup .mname').val('');
        $('#e-d-new-coord-popup .bday').val('');
        $('#e-d-new-coord-popup .date-emp').val('');
        $('#e-d-new-coord-popup .address-container .address-1').val('');
        $('#e-d-new-coord-popup .address-container .address-2').val('').parent().addClass('hide');
        $('#e-d-new-coord-popup .address-container .address-3').val('').parent().addClass('hide');
        $('#e-d-new-coord-popup .email-container .email-1').val('');
        $('#e-d-new-coord-popup .email-container .email-2').val('').parent().addClass('hide');
        $('#e-d-new-coord-popup .contact-no-container .contact-1').val('');
        $('#e-d-new-coord-popup .contact-no-container .contact-2').val('').parent().addClass('hide');
        $('#e-d-new-coord-popup .contact-no-container .contact-3').val('').parent().addClass('hide');
    });
    $('#e-d-new-coord-popup .add-a-row').click(function() {
        if($('#e-d-new-coord-popup .address-container .address-1').parent().hasClass('hide')){
            $('#e-d-new-coord-popup .address-container .address-1').parent().removeClass('hide');
        }else if($('#e-d-new-coord-popup .address-container .address-2').parent().hasClass('hide')){
            $('#e-d-new-coord-popup .address-container .address-2').parent().removeClass('hide');
        }else if($('e-d-new-coord-popup .address-container .address-3').parent().hasClass('hide')){
            $('#e-d-new-coord-popup .address-container .address-3').parent().removeClass('hide');
        }
    });
    $('#e-d-new-coord-popup .address-container .btn-remove-row').click(function() {
        $('#e-d-new-coord-popup input.error').removeClass('error');
        $('#e-d-new-coord-popup label.error').remove();
        $(this).parent().siblings().val('');
        $(this).parent().parent().addClass('hide');
    });
    $('#e-d-new-coord-popup .add-e-row').click(function() {
        if($('#e-d-new-coord-popup .email-container .email-1').parent().hasClass('hide')){
            $('#e-d-new-coord-popup .email-container .email-1').parent().removeClass('hide');
        }else if($('#e-d-new-coord-popup .email-container .email-2').parent().hasClass('hide')){
            $('#e-d-new-coord-popup .email-container .email-2').parent().removeClass('hide');
        }
    });
    $('#e-d-new-coord-popup .email-container .btn-remove-row').click(function() {
        $('#e-d-new-coord-popup input.error').removeClass('error');
        $('#e-d-new-coord-popup label.error').remove();
        $(this).parent().siblings().val('');
        $(this).parent().parent().addClass('hide');
    });
    $('#e-d-new-coord-popup .add-c-row').click(function() {
        if($('#e-d-new-coord-popup .contact-no-container .contact-1').parent().hasClass('hide')){
            $('#e-d-new-coord-popup .contact-no-container .contact-1').parent().removeClass('hide');
        }else if($('#e-d-new-coord-popup .contact-no-container .contact-2').parent().hasClass('hide')){
            $('#e-d-new-coord-popup .contact-no-container .contact-2').parent().removeClass('hide');
        }else if($('#e-d-new-coord-popup .contact-no-container .contact-3').parent().hasClass('hide')){
            $('#e-d-new-coord-popup .contact-no-container .contact-3').parent().removeClass('hide');
        }
    });
    $('#e-d-new-coord-popup .contact-no-container .btn-remove-row').click(function() {
        $('#e-d-new-coord-popup input.error').removeClass('error');
        $('#e-d-new-coord-popup label.error').remove();
        $(this).parent().siblings().val('');
        $(this).parent().parent().addClass('hide');
    });
    // proceed to event supplier
    $('#event-details-tab #event-details-form').validate({
        rules: {
            event_name: 'required',
            event_budget: 'number',
            start_date: {
                required: true,
                dateISO: true,
            },
            end_date: {
                required: true,
                dateISO: true,
            },
            actual_date: {
                required: true,
                dateISO: true,
            }
        }, 
        groups: {
            actual_time: 'a_hr a_min',
        },
        errorPlacement: function(error, element) {
            var name = element.prop('name');
            if ( name === 'a_hr' || name === 'a_min') {
                error.insertAfter('#event-details-tab #event-details-form .actual-time');
            } else {
                error.insertAfter(element);
            }
        },
        submitHandler: function(form) {
//            var eventLoc = new Array();
//            $('#event-details-tab .venue-checkbox:checked').each(function() {
//                eventLoc.push($(this).parent().text() + '-' + $(this).val());
//            });
//            var eventDetails = {
//                'event_name': $('#event-details-tab .event-name').val(),
//                'event_type': $('#event-details-tab .event-type-select option:selected').text() + '-' +
//                        $('#event-details-tab .event-type-select option:selected').val(),
//                'event_client': $('#event-details-tab .client-select option:selected').text() + '-' +
//                        $('#event-details-tab .client-select option:selected').val(),
//                'event_start_date': $('#event-details-tab .s-year').val() + '-' + $('#event-details-tab .s-month').val() +
//                        '-' + $('#event-details-tab .s-day').val(),
//                'event_end_date': $('#event-details-tab .e-year').val() + '-' + $('#event-details-tab .e-month').val() +
//                        '-' + $('#event-details-tab .e-day').val(),
//                'event_loc': eventLoc.join(';'),
//                'event_coord': $('#event-details-tab .coordinator-select').text() + '-' +
//                        $('#event-details-tab .coordinator-select').val(),
//                'event_note': $('#event-details-tab .event-note').val()
//            };
//            localStorage.setItem('eventDetails', JSON.stringify(eventDetails));
            $('#create-event-nav li:eq(1) a').tab('show');
            $('#e-d-new-coord-popup input.error').removeClass('error');
            $('#e-d-new-coord-popup label.error').remove();
            return false;
        }
    });
    // Event Supplier
    $('#event-supplier-tab .btn-reset-event-supplier').click(function() {
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'event/get/event-supplier',
            type: 'post',
            dataType: 'json',
            success: function(data) {
                $('#event-supplier-tab #event-supplier-list').empty();
                $.each(data, function(key, value) {
                    $('#event-supplier-tab #event-supplier-list').
                            append('<div class="list-group" style="padding:1em;border: solid 1px #cccccc;">' +
                            '<h4 class="list-group-item-heading">Company Name: ' + value.company + '</h4>' +
                            '<p class="list-group-item-text">Contact Person: ' + value.contact_person + '</p>' +
                            '<p class="list-group-item-text">Available Services: <span class="available-services">' + value.services + '</span></p>' +
                            '<p class="list-group-item-text">Services chosen: <span class="services-chosen"></span></p>' +
                            '<div class="btn-group pull-right">' +
                            '<a href="#services-popup" data-toggle="modal" class="btn-assign-services" data-supplierid="' + value.supplier_id + '">Services</a>' +
                            '</div><div class="clearfix"></div></div>');
                });
                $('.loading-container').addClass('hide');
            },
            error: function(xhr, status) {
                $('.loading-container').addClass('hide');
            }
        });
    });
    // new supplier
    $('#e-s-new-supplier-popup #supplier-form').validate({
        rules: {
            cname: 'required',
            contact_person: 'required',
            address_1: 'required',
            email_1: {
                required: true,
                email: true,
            },
            email_2: 'email',
            contact_no_1: {
                required: true,
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
            contact_no_2: {
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
            contact_no_3: {
                digits: true,
                minlength: 11,
                maxlength: 11,
            },
        },
        submitHandler: function(form) {
            var services = new Array();
            var address = new Array();
            var email = new Array();
            var contact = new Array();
            $('#e-s-new-supplier-popup .services-container .services-text').each(function() {
                if ($(this).val() != '') {
                    services.push($(this).val());
                }
            });
            $('#e-s-new-supplier-popup .address-container .address-text').each(function() {
                if ($(this).val() != '') {
                    address.push($(this).val());
                }
            });
            $('#e-s-new-supplier-popup .email-container .email-text').each(function() {
                if ($(this).val() != '') {
                    email.push($(this).val());
                }
            });
            $('#e-s-new-supplier-popup .contact-no-container .contact-no-text').each(function() {
                if ($(this).val() != '') {
                    contact.push($(this).val());
                }
            });
            var supplier = {
                'cname': $('#e-s-new-supplier-popup .cname').val(),
                'contact_person': $('#e-s-new-supplier-popup .contact-person').val(),
                'services': services.join(';'),
                'address': address.join(';'),
                'email': email.join(';'),
                'contact_no': contact.join(';'),
                'action': 0,
            };
            save_supplier(supplier, $('#e-s-new-supplier-popup').attr('id'));
            return false;
        }
    });
    $('#e-s-new-supplier-popup .supplier-form .another-services').click(function() {
        new_services_row($('#e-s-new-supplier-popup').attr('id'), 'supplier-form');
    });
    $('#e-s-new-supplier-popup').on('click', '.btn-remove-services', function() {
        $(this).parent().parent().remove();
    });
    $('#e-s-new-supplier-popup').on('hide.bs.modal', function() {
        $('#e-s-new-supplier-popup input.error').removeClass('error');
        $('#e-s-new-supplier-popup label.error').remove();
        $('#e-s-new-supplier-popup .cname').val('');
        $('#e-s-new-supplier-popup .contact-person').val('');
        $('#e-s-new-supplier-popup .services-container .services-text').val('');
        $('#e-s-new-supplier-popup .services-container').find('.d-services').parent().remove();
        $('#e-s-new-supplier-popup .address-container .address-text').val('');
        $('#e-s-new-supplier-popup .email-container .email-text').val('');
        $('#e-s-new-supplier-popup .contact-no-container .contact-no-text').val('');
    });
    $('#event-supplier-list').on('click', '.btn-assign-services', function() {
        $('#services-popup #supplier-id').val($(this).attr('data-supplierid'));
        $(this).addClass('currently-viewed');
    });
    $('#services-popup').on('show.bs.modal', function() {
        var $chosenServices = $('#event-supplier-tab #event-supplier-list .currently-viewed').
                parent().parent().children().children('.services-chosen').text();
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'event/get/services',
            type: 'post',
            data: {'supplier_id': $('#services-popup #supplier-id').val()},
            dataType: 'json',
            success: function(data) {
                var services = data.services.split(';');
                $('#services-popup .services-container .panel-body').empty();
                for (var i = 0; i < services.length; i++) {
                    if ($chosenServices.indexOf(services[i]) > -1) {
                        $('#services-popup .services-container .panel-body').
                                append('<label><input type="checkbox" class="services-checkbox" checked="checked" /> ' + services[i] + '</label>&nbsp;&nbsp;');
                    } else {
                        $('#services-popup .services-container .panel-body').
                                append('<label><input type="checkbox" class="services-checkbox" /> ' + services[i] + '</label>&nbsp;&nbsp;');
                    }
                }
                $('.loading-container').addClass('hide');
            },
            error: function(xhr, status) {
                $('.loading-container').addClass('hide');
            }
        });
    });
    $('#services-popup').on('hide.bs.modal', function() {
        $('#services-popup .services-container .panel-body').empty();
        $('#services-popup .service-name').val('');
        $('#e-d-new-coord-popup input.error').removeClass('error');
        $('#e-d-new-coord-popup label.error').remove();
        $('#event-supplier-tab #event-supplier-list .currently-viewed').removeClass('currently-viewed');
    });
    // add new service
    $('#services-popup #services-form').validate({
        rules: {
            service: 'required',
        },
        submitHandler: function(form) {
            var service = {
                'service': $('#services-popup .service-name').val(),
                'supplier_id': $('#services-popup #supplier-id').val(),
            };
            var data = new Array();
            $('#services-popup .services-container .panel-body .services-checkbox').each(function() {
                data.push($(this).parent().text().replace(/\s+/g, ''));
            });
            if ($.inArray(service.service, data) == -1) {
                $('.loading-container').removeClass('hide');
                $.ajax({
                    url: $url + 'event/save/service',
                    type: 'post',
                    data: service,
                    dataType: 'json',
                    success: function(data) {
                        if (data.status == 'success') {
                            $('#services-popup .alert-success').remove();
                            $('#services-popup .alert-danger').remove();
                            $('#services-popup .services-container .panel-body').
                                    append('<label><input type="checkbox" class="services-checkbox" /> ' + service.service + '</label>&nbsp;&nbsp;');
                            $('#services-popup .modal-body').prepend('<div class="alert alert-success">' + data.msg + '</div>');
                            success_msg();
                            var $text = $('#event-supplier-tab #event-supplier-list').find('.currently-viewed').
                                    parent().parent().children().children('.available-services').text();
                            $('#event-supplier-tab #event-supplier-list').find('.currently-viewed').
                                    parent().parent().children().children('.available-services').text($text + ';' + service.service);
                            $('#services-popup .service-name').val('');
                            $('#services-popup input.error').removeClass('error');
                            $('#services-popup label.error').remove();
                            $('.loading-container').addClass('hide');
                        } else {
                            $('#services-popup .alert-success').remove();
                            $('#services-popup .alert-danger').remove();
                            $('#services-popup .modal-body').prepend('<div class="alert alert-danger">' + data.msg + '</div>');
                            error_msg();
                            $('#services-popup input.error').removeClass('error');
                            $('#services-popup label.error').remove();
                            $('.loading-container').addClass('hide');
                        }
                    },
                    error: function() {
                        $('#services-popup .alert-success').remove();
                        $('#services-popup .alert-danger').remove();
                        $('#services-popup .modal-body').prepend('<div class="alert alert-danger">Something went wrong while saving the service. Please try again later.</div>');
                        error_msg();
                        $('#services-popup input.error').removeClass('error');
                        $('#services-popup label.error').remove();
                        $('.loading-container').addClass('hide');
                    }
                });
            } else {
                $('#services-popup .alert-success').remove();
                $('#services-popup .alert-danger').remove();
                $('#services-popup .modal-body').prepend('<div class="alert alert-danger">Service already exist.</div>');
                error_msg();
            }
            return false;
        },
        errorPlacement: function(error, element) {
            $('#services-popup input.error').removeClass('error');
            $('#services-popup label.error').remove();
            error.insertAfter(element.parent().parent());
        },
    });
    // assign services
    $('#services-popup .btn-assign').click(function() {
        var $checked = $('#services-popup .services-container .panel-body .services-checkbox:checked').size();
        var pick = new Array();
        $('#services-popup .services-container .panel-body .services-checkbox:checked').each(function() {
            pick.push($(this).parent().text());
        });
        if ($checked > 0) {
            $('#event-supplier-tab #event-supplier-list').find('.currently-viewed').
                    parent().parent().css('background-color', '#99ff99');
            $('#event-supplier-tab #event-supplier-list').find('.currently-viewed').
                    parent().parent().children().children('.services-chosen').text(pick.join(';'));
            if (!$('#event-supplier-tab #event-supplier-list .currently-viewed').
                    parent().children('.unassign-supplier').hasClass('unassign-supplier')) {
                $('#event-supplier-tab #event-supplier-list').find('.currently-viewed').
                        parent().append('<span class="separator"> | </span><a class="unassign-supplier">Unasign supplier</a>');
            }
            $('#services-popup').modal('hide');
        } else {
            $('#event-supplier-tab #event-supplier-list').find('.currently-viewed').
                    parent().parent().css('background-color', '#ffffff').children().
                    children('services-chosen').text('');
            $('#event-supplier-tab #event-supplier-list').find('.currently-viewed').
                    parent().parent().children().children('.services-chosen').text('');
            $('#event-supplier-tab #event-supplier-list .currently-viewed').siblings('.unassign-supplier').remove();
            $('#event-supplier-tab #event-supplier-list .currently-viewed').siblings('.separator').remove();
            $('#services-popup').modal('hide');
        }
    });
    $('#event-supplier-tab #event-supplier-list').on('click', '.unassign-supplier', function() {
        $(this).parent().parent().css('background-color', '#ffffff');
        $(this).parent().siblings().children('.services-chosen').text('');
        $(this).siblings('.separator').remove();
        $(this).remove();
    });
    $('#event-supplier-tab .btn-proceed-event-checklist').click(function() {
        var eventSupplier = new Array();
        var eventSup = {
            'event_supplier': eventSupplier,
        };
        $('#create-event-nav li:eq(2) a').tab('show');
        $('#event-supplier-list .list-group').has('.unassign-supplier').each(function() {
            eventSupplier.push($(this).children().children('.btn-assign-services').attr('data-supplierid') + '-' +
                    $(this).children().children('.services-chosen').text());
        });
        localStorage.setItem('event_supplier', JSON.stringify(eventSup));
    });
    $('#event-supplier-tab .btn-back-event-details').click(function() {
        $('#create-event-nav li:eq(0) a').tab('show');
    });
    // Event Checklist
    // new category
    $('#event-checklist-tab #category-form').validate({
        rules: {
            category_name: 'required',
        },
        submitHandler: function(form) {
            $('.loading-container').removeClass('hide');
            $.ajax({
                url: $url + 'general-checklist/save-new-cat',
                type: 'post',
                dataType: 'json',
                data: {'category': $('#event-checklist-tab .new-category-form .category-name').val()},
                success: function(data) {
                    if (data.status === 'success') {
                        $('#event-checklist-tab #event-checklist-list').prepend('<div class="panel panel-default">' +
                                '<div class="panel-heading" data-catid="' + data.cat.category_id + '">' +
                                '<a class="show-sub-cat" title="Show sub category"><span class="glyphicon glyphicon-chevron-right"></span></a>' +
                                data.cat.category_name +
                                '<a class="remove-cat pull-right" title="Remove category"><span class="glyphicon glyphicon-remove"></span></a>' +
                                '</div></div>');
                        $('#event-checklist-tab .new-category-form .category-name').val('');
                        $('#event-checklist-tab input.error').removeClass('error');
                        $('#event-checklist-tab label.error').remove();
                        $('.alert-danger').remove();
                        $('.alert-success').remove();
                        $('#event-checklist-tab').prepend('<div class="alert alert-success">' + data.msg + '</div>');
                        success_msg();
                        $('.loading-container').addClass('hide');
                    } else {
                        $('#event-checklist-tab input.error').removeClass('error');
                        $('#event-checklist-tab label.error').remove();
                        $('.alert-danger').remove();
                        $('.alert-success').remove();
                        $('#event-checklist-tab').prepend('<div class="alert alert-danger">' + data.msg + '</div>');
                        error_msg();
                        $('.loading-container').addClass('hide');
                    }
                },
                error: function() {
                    $('.alert-danger').remove();
                    $('.alert-success').remove();
                    $('#event-checklist-tab').prepend('<div class="alert alert-danger">Something went wrong while saving the category. Please try again later.</div>');
                    error_msg();
                    $('.loading-container').addClass('hide');
                }
            });
            return false;
        },
        errorPlacement: function(error, element) {
            $('#event-checklist-tab input.error').removeClass('error');
            $('#event-checklist-tab label.error').remove();
            error.insertAfter(element.parent().parent().parent().parent());
        }
    });
    $('#event-checklist-tab').on('click', '.show-sub-cat', function() {
        var $catId = $(this).parent().attr('data-catid');
        if ($(this).hasClass('show-sub-cat')) {
            $(this).removeClass('show-sub-cat').addClass('hide-sub-cat');
            $(this).children().removeClass('glyphicon-chevron-up').addClass('glyphicon-chevron-down');
            $(this).attr('title', 'Hide sub category');
            if (!$(this).parent().siblings().hasClass('panel-body')) {
                $(this).parent().after('<div class="panel-body"><div class="new-sub-cat-form"><div class="input-group">' +
                        '<input type="text" class="form-control sub-category-name required" name="sub_category_name" placeholder="New Sub Category...">' +
                        '<span class="input-group-btn">' +
                        '<button class="btn btn-default btn-new-sub-cat"><span class="glyphicon glyphicon-plus"></span></button>' +
                        '</span>' +
                        '</div></div></div>');
                var $display = $(this).parent().siblings();
                $('.loading-container').removeClass('hide');
                $.ajax({
                    url: $url + 'general-checklist/sub-cat/' + $catId,
                    type: 'post',
                    dataType: 'json',
                    success: function(sub_cat) {
                        if (sub_cat !== false) {
                            $.each(sub_cat, function(key, value) {
                                $display.append('<a class="list-group-item sub-cat-item" data-subcatid="' +
                                        value.checklist_id + '">' + value.list_description +
                                        '<span class="glyphicon glyphicon-remove pull-right btn-remove-sub-cat"></span></a>');
                            });
                        } else {
                            if ($display.find('.empty-msg').length === 0) {
                                $display.append('<a href="#" class="list-group-item empty-msg">Oops! No sub category found.</a>');
                            }
                        }
                        $('.loading-container').addClass('hide');
                    },
                    error: function(xhr, status) {
                        $('.loading-container').addClass('hide');
                    }
                });
            } else {
                $(this).parent().siblings().show();
            }
        }
    });
    $('#event-checklist-tab').on('click', '.hide-sub-cat', function() {
        if ($(this).hasClass('hide-sub-cat')) {
            $(this).removeClass('hide-sub-cat').addClass('show-sub-cat');
            $(this).children().removeClass('glyphicon-chevron-down').addClass('glyphicon-chevron-right');
            $(this).attr('title', 'Show sub category');
            $(this).parent().siblings().hide();
        }
    });
    $('#event-checklist-tab').on('click', '.remove-cat', function() {
        $(this).parent().parent().remove();
    });
    $('#event-checklist-tab .btn-reset-event-checklist').click(function() {
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'event/get/event-category',
            type: 'post',
            dataType: 'json',
            success: function(data) {
                $('#event-checklist-tab #event-checklist-list').empty();
                $.each(data, function(key, value) {
                    $('#event-checklist-tab #event-checklist-list').
                            append(' <div class="panel panel-default">' +
                            '<div class="panel-heading" data-catid="' + value.category_id + '">' +
                            '<a class="show-sub-cat" title="Show sub category"><span class="glyphicon glyphicon-chevron-up"></span></a> ' +
                            value.category_name + '<a class="remove-cat pull-right" title="Remove category"><span class="glyphicon glyphicon-remove"></span></a>' +
                            '</div></div>');
                });
                $('.loading-container').addClass('hide');
            },
            error: function() {
            }
        });
    });
    $('#event-checklist-tab #event-checklist-list').on('click', '.btn-new-sub-cat', function() {
        var $current = $(this).parent().parent().parent().parent();
        var $target = $(this).parent().parent().parent();
        var sub_cat = {
            'sub_category': $(this).parent().siblings().val(),
            'cat_id': $(this).parent().parent().parent().parent().siblings().attr('data-catid'),
        };
        if ($(this).parent().siblings().val() !== '') {
            $('.loading-container').removeClass('hide');
            $.ajax({
                url: $url + 'general-checklist/save-new-sub-cat',
                type: 'post',
                dataType: 'json',
                data: sub_cat,
                success: function(data) {
                    if (data.status === 'success') {
                        $target.after('<a class="list-group-item sub-cat-item" data-subcatid="' + data.sub_cat.checklist_id +
                                '">' + data.sub_cat.list_description +
                                '<span class="glyphicon glyphicon-remove pull-right btn-remove-sub-cat"></span></a>');
                        $current.val('');
                        $current.find('.empty-msg').remove();
                        $('.new-sub-cat-form').find('.required-error').remove();
                        $('.alert-danger').remove();
                        $('.alert-success').remove();
                        $current.prepend('<div class="alert alert-success">' + data.msg + '</div>');
                        success_msg();
                        $('.loading-container').addClass('hide');
                    } else {
                        $('.alert-danger').remove();
                        $('.alert-success').remove();
                        $current.prepend('<div class="alert alert-danger">' + data.msg + '</div>');
                        error_msg();
                        $('.loading-container').addClass('hide');
                    }
                },
                error: function() {
                    $('.alert-danger').remove();
                    $('.alert-success').remove();
                    $current.prepend('<div class="alert alert-danger">Something went wrong while saving the category. Please try again later.</div>');
                    error_msg();
                    $('.loading-container').addClass('hide');
                }
            });
        } else {
            if (!$('#event-checklist-tab .new-sub-cat-form p').hasClass('required-error')) {
                $('#event-checklist-tab .new-sub-cat-form').append('<label class="required-error">This field is required.</label>');
            }
        }
    });
    $('#event-checklist-tab #event-checklist-list').on('click', '.btn-remove-sub-cat', function() {
        $(this).parent().remove();
    });
    $('#event-checklist-tab .btn-proceed-event-task').click(function() {
        var subCatId = new Array();
        $('#event-checklist-tab .panel-default').each(function() {
            if ($(this).children('.panel-body').hasClass('panel-body')) {
                $(this).children('.panel-body').children('.sub-cat-item').each(function() {
                    subCatId.push($(this).attr('data-subcatid'));
                });
            } else {
                getSubCatId($(this).children('.panel-heading').attr('data-catid'))
                        .done(function(subCat) {
                    $.each(subCat, function(key, value) {
                        subCatId.push(value.checklist_id);
                    });
                    localStorage.setItem('event_checklist', subCatId);
                })
                        .fail(function(x) {
                });
            }
        });
        $('#create-event-nav li:eq(3) a').tab('show');
    });
    function getSubCatId(catId) {
        return $.ajax({
            url: $url + 'general-checklist/sub-cat/' + catId,
            type: 'post',
            dataType: 'json'
        });
    }
    $('#event-checklist-tab .btn-back-event-supplier').click(function() {
        $('#create-event-nav li:eq(1) a').tab('show');
    });
    // Event Task
    $('#add-event-task-popup #event-task-form').validate({
        rules: {
            task_desc: 'required',
            task_date: {
                required: true,
                dateISO: true,
            }
        },
        groups: {
            actual_time: 'task_hr task_min',
        },
        errorPlacement: function(error, element) {
            var name = element.prop('name');
            if (name === 'task_date' || name === 'task_hr' || name === 'task_min') {
                $('#add-event-task-popup .task-date-time').after(error);
            } else {
                error.insertAfter(element);
            }
        },
        submitHandler: function(form) {
            var eventTask = {
                'task_desc': $('#add-event-task-popup .task-desc').val(),
                'task_date': $('#add-event-task-popup .task-date').val(),
                'task_hr': $('#add-event-task-popup .task-hr option:selected').text(),
                'task_min': $('#add-event-task-popup .task-min option:selected').text(),
            };
            $('#event-task-tab .event-task-list').
                    prepend('<div class="list-group col-md-6" style="padding:1em;border: solid 1px #cccccc;">' +
                    '<p class="list-group-item-text">Task: <span class="task-desc">' + eventTask.task_desc + '</span></p>' +
                    '<p class="list-group-item-text">Date and Time: <span class="task-date">' + eventTask.task_date + '</span> <span class="task-time">' + eventTask.task_hr + ':' + eventTask.task_min + '</span></p>' +
                    '<div class="btn-group pull-right">' +
                    '<a class="btn-remove-task">Remove task</a>' +
                    '</div><div class="clearfix"></div></div>');
            $('#add-event-task-popup').modal('hide');
            return false;
        }
    });
    $('#add-event-task-popup .task-date').datepicker({
        autoclose: true,
        format: "yyyy-dd-mm",
        todayHighlight: true,
    });
    $('#add-event-task-popup').on('hide.bs.modal', function() {
        $('#add-event-task-popup .task-desc').val('');
        //$('#add-event-task-popup .task-date').val('');
        $('#add-event-task-popup .task-hr').find('.default-hr').prop('selected', true);
        $('#add-event-task-popup .task-min').find('.default-min').prop('selected', true);
        $('#add-event-task-popup input.error').removeClass('error');
        $('#add-event-task-popup label.error').remove();
    });
    $('#event-task-tab .event-task-list').on('click', '.btn-remove-task', function() {
        $(this).parent().parent().remove();
    });
    $('#event-task-tab .btn-back-event-checklist').click(function() {
        $('#create-event-nav li:eq(2) a').tab('show');
    });
    $('#event-task-tab .btn-finish').click(function() {
        var eventLoc = new Array();
        var eventSupplier = new Array();
        var eventTask = new Array();
        $('#event-details-tab .venue-checkbox:checked').each(function() {
            eventLoc.push($(this).val());
        });
        $('#event-supplier-list .list-group').has('.unassign-supplier').each(function() {
            eventSupplier.push($(this).children().children('.btn-assign-services').attr('data-supplierid') + '-' +
                    $(this).children().children('.services-chosen').text());
        });
        $('#event-task-tab .list-group').each(function() {
            eventTask.push($(this).children().children('.task-desc').text() +
                    ';' + $(this).children().children('.task-date').text() + ';' +
                    $(this).children().children('.task-time').text() + ':00');
        });
        var eventDetails = {
            'event_name': $('#event-details-tab .event-name').val(),
            'event_budget': $('#event-details-tab .event-budget').val(),
            'event_type': $('#event-details-tab .event-type-select option:selected').val(),
            'event_client': $('#event-details-tab .client-select option:selected').val(),
            'event_start_date': $('#event-details-tab .start-date').val(),
            'event_end_date': $('#event-details-tab .end-date').val(),
            'event_actual_date': $('#event-details-tab .actual-date').val() + ' ' + $('#event-details-tab .a-hr').val() + ':' +
                    $('#event-details-tab .a-min').val() + ':00',
            'event_loc': eventLoc,
            'event_coord': $('#event-details-tab .coordinator-select option:selected').val(),
            'event_note': $('#event-details-tab .event-desc').val(),
            'event_checklist': localStorage.getItem('event_checklist'),
            'event_supplier': eventSupplier,
            'event_task': eventTask,
        };
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'event/save',
            type: 'post',
            data: eventDetails,
            dataType: 'json',
            success: function(data) {
                if (data.status == 'success') {
                    window.location = $url + 'events/calendar/' + yr + '/' + month;
                    $('.loading-container').addClass('hide');
                }
            },
            error: function(xhr, status) {
                $('.loading-container').addClass('hide');
            }
        });
    });
// Functions--------------------------------------------------------------------
    // Contacts
    // Employees functions------------------------------------------------------
    // get employee
    function get_emp(empId) {
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'employee/view/' + empId,
            type: 'post',
            dataType: 'json',
            success: function(data) {
                if (data != false) {
                    var g = '';
                    if (data.gender == '0') {
                        g = 'Male';
                    } else {
                        g = 'Female';
                    }
                    $('#view-emp-popup #emp-id').val(data.coordinator_id);
                    $('#view-emp-popup .view-emp-container .name').text(data.coord_lname + ', ' + data.coord_fname + ' ' + data.coord_mname);
                    $('#view-emp-popup .view-emp-container .bday').text(data.coord_bday);
                    $('#view-emp-popup .view-emp-container .gender').text(g);
                    $('#view-emp-popup .view-emp-container .address').text(data.coord_address);
                    $('#view-emp-popup .view-emp-container .email').text(data.coord_email);
                    $('#view-emp-popup .view-emp-container .contact').text(data.coord_num);
                    $('#view-emp-popup .edit-emp-container .lname').val(data.coord_lname);
                    $('#view-emp-popup .edit-emp-container .fname').val(data.coord_fname);
                    $('#view-emp-popup .edit-emp-container .mname').val(data.coord_mname);
                    $('#view-emp-popup .edit-emp-container .bday-month option[value=' + data.month + ']').prop('selected', true);
                    $('#view-emp-popup .edit-emp-container .bday-day option[value=' + data.day + ']').prop('selected', true);
                    $('#view-emp-popup .edit-emp-container .bday-year option[value=' + data.year + ']').prop('selected', true);
                    $('#view-emp-popup .edit-emp-container .date-emp').val(data.emp_date);
                    if (data.gender == '0') {
                        $('#view-emp-popup .edit-emp-container .male').attr('checked', true).parent().addClass('active');
                        $('#view-emp-popup .edit-emp-container .female').attr('checked', false).parent().removeClass('active');
                    } else {
                        $('#view-emp-popup .edit-emp-container .female').attr('checked', true).parent().addClass('active');
                        $('#view-emp-popup .edit-emp-container .male').attr('checked', false).parent().removeClass('active');
                    }
                    var address = data.coord_address.split(';');
                    var email = data.coord_email.split(';');
                    var contact = data.coord_num.split(';');
                    $('#view-emp-popup .edit-emp-container .address-1').val(address[0]);
                    $('#view-emp-popup .edit-emp-container .address-2').val(address[1]);
                    $('#view-emp-popup .edit-emp-container .address-3').val(address[2]);
                    $('#view-emp-popup .edit-emp-container .email-1').val(email[0]);
                    $('#view-emp-popup .edit-emp-container .email-2').val(email[1]);
                    $('#view-emp-popup .edit-emp-container .contact-1').val(contact[0]);
                    $('#view-emp-popup .edit-emp-container .contact-2').val(contact[1]);
                    $('#view-emp-popup .edit-emp-container .contact-3').val(contact[2]);
                    $('.loading-container').addClass('hide');
                } else {
                    $('#view-emp-popup').modal('hide');
                    $('.alert-danger').remove();
                    $('.alert-success').remove();
                    $('.contacts-container').prepend('<div class="alert alert-danger margin-top">Something went wrong while fetching the employee information. Please try again later.</div>');
                    error_msg();
                    $('.loading-container').addClass('hide');
                }
            },
            error: function() {
                $('#view-emp-popup').modal('hide');
                $('.alert-danger').remove();
                $('.alert-success').remove();
                $('.contacts-container').prepend('<div class="alert alert-danger margin-top">Something went wrong while fetching the employee information. Please try again later.</div>');
                error_msg();
                $('.loading-container').addClass('hide');
            }
        });
    }
    // save employee
    function save_emp(emp, trigger) {
        var item = trigger.split('-');
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'employee/save',
            type: 'post',
            data: emp,
            dataType: 'json',
            success: function(data) {
                if (data.status === 'success') {
                    if (item[0] === 'new') {
                        $('.alert-danger').remove();
                        $('.alert-success').remove();
                        $('.contacts-container').prepend('<div class="alert alert-success margin-top">' + data.msg + '</div>');
                        refresh_employees_table();
                        success_msg();
                        $('#' + trigger).modal('hide');
                        $('.loading-container').addClass('hide');
                    } else if (item[0] === 'view') {
                        $('.alert-danger').remove();
                        $('.alert-success').remove();
                        $('.contacts-container').prepend('<div class="alert alert-success margin-top">' + data.msg + '</div>');
                        refresh_employees_table();
                        success_msg();
                        $('#' + trigger).modal('hide');
                        $('.loading-container').addClass('hide');
                    } else if (trigger == 'e-d-new-coord-popup') {
                        $('.alert-danger').remove();
                        $('.alert-success').remove();
                        $('#event-details-tab .coordinator-select').append('<option value="' + data.emp.coordinator_id + '">' +
                                data.emp.coord_lname + ', ' + data.emp.coord_fname + ' ' + data.emp.coord_mname + '</option>');
                        $('.create-event-container').prepend('<div class="alert alert-success margin-top">' + data.msg + '</div>');
                        success_msg();
                        $('#' + trigger).modal('hide');
                        $('.loading-container').addClass('hide');
//                    } else if (trigger == 'e-d-new-coord-popup') {
//                        $('.alert-danger').remove();
//                        $('.alert-success').remove();
//                        $('#event-details-tab .coordinator-select').append('<option value="' + data.emp.coordinator_id + '">' +
//                                data.emp.lname + ', ' + data.emp.fname + ' ' + data.emp.mname + '</option>');
//                        $('.create-event-container').prepend('<div class="alert alert-success margin-top">' + data.msg + '</div>');
//                        success_msg();
//                        $('#' + trigger).modal('hide');
//                        $('.loading-container').addClass('hide');
                    } else if (trigger === 'view-event-details-tab') {
                        $('.alert').remove();
                        $('.edit-event-details-container .coordinator-select').append('<option value="' + data.emp.coordinator_id + '">' +
                                data.emp.coord_lname + ', ' + data.emp.coord_fname + '</option>');
                        $('.edit-event-details-container #emp-form .lname').val('');
                        $('.edit-event-details-container #emp-form .fname').val('');
                        $('.edit-event-details-container #emp-form .mname').val('');
                        $('.edit-event-details-container #emp-form .bday-month .default-month').prop('selected', true);
                        $('.edit-event-details-container #emp-form .bday-day .default-day').prop('selected', true);
                        $('.edit-event-details-container #emp-form .bday-year .default-year').prop('selected', true);
                        $('.edit-event-details-container #emp-form .date-emp').val('');
                        $('.edit-event-details-container #emp-form .address-text').val('');
                        $('.edit-event-details-container #emp-form .email-text').val('');
                        $('.edit-event-details-container #emp-form .contact-no-text').val('');
                        $('#view-event-details-tab .new-e-e-container').addClass('hide').siblings('.form-sep').remove();
                        $('#view-event-details-tab hr').after('<div class="alert alert-success margin-top">' + data.msg + '</div>');
                        remove_alert();
                        $('.loading-container').addClass('hide');
                    }
                } else {
                    if (trigger == 'e-d-new-coord-popup') {
                        if (data.emp == 'already exist') {
                            $('.alert-danger').remove();
                            $('.alert-success').remove();
                            $('#e-d-new-coord-popup #emp-form').before('<div class="alert alert-danger">' + data.msg + '</div>');
                            error_msg();
                        } else {
                            $('#' + trigger).modal('hide');
                            $('.alert-danger').remove();
                            $('.alert-success').remove();
                            $('.create-event-container').prepend('<div class="alert alert-danger margin-top">' + data.msg + '</div>');
                            error_msg();
                        }
                        $('.loading-container').addClass('hide');
                    } else if (trigger === 'view-event-details-tab') {
                        if (data.emp === 'already exist') {
                            $('.alert-danger').remove();
                            $('.alert-success').remove();
                            $('#view-event-details-tab hr').after('<div class="alert alert-danger margin-top">' + data.msg + '</div>');
                            error_msg();
                        } else {
                            $('.alert-danger').remove();
                            $('.alert-success').remove();
                            $('#view-event-details-tab hr').after('<div class="alert alert-danger margin-top">' + data.msg + '</div>');
                            error_msg();
                        }
                        $('.loading-container').addClass('hide');
                    } else {
                        if (data.emp == 'already exist') {
                            $('.alert-danger').remove();
                            $('.alert-success').remove();
                            $('#new-emp-popup #emp-form').before('<div class="alert alert-danger">' + data.msg + '</div>');
                            error_msg();
                        } else {
                            $('.alert-danger').remove();
                            $('.alert-success').remove();
                            $('.contacts-container').prepend('<div class="alert alert-danger margin-top">' + data.msg + '</div>');
                            error_msg();
                            $('#' + trigger).modal('hide');
                        }
                        $('.loading-container').addClass('hide');
                    }
                }
            },
            error: function() {
                if (trigger == 'e-d-new-coord-popup') {
                    $('.alert-danger').remove();
                    $('.alert-success').remove();
                    $('.create-event-container').prepend('<div class="alert alert-danger margin-top">Something went wrong while performing changes to the employee. Please try again later.</div>');
                    error_msg();
                    $('#' + trigger).modal('hide');
                    $('.loading-container').addClass('hide');
                } else if (trigger === 'view-event-details-tab') {
                    $('.alert-danger').remove();
                    $('.alert-success').remove();
                    $('#view-event-details-tab hr').after('<div class="alert alert-danger margin-top">Something went wrong while performing changes to the employee. Please try again later.</div>');
                    error_msg();
                    $('.loading-container').addClass('hide');
                } else {
                    $('.alert-danger').remove();
                    $('.alert-success').remove();
                    $('.contacts-container').prepend('<div class="alert alert-danger margin-top">Something went wrong while performing changes to the employee. Please try again later.</div>');
                    error_msg();
                    $('#' + trigger).modal('hide');
                    $('.loading-container').addClass('hide');
                }
            }
        });
    }
    // repopulate employees table
    function refresh_employees_table() {
        $('#employees-table').dataTable({
            "bDestroy": true,
            "bProcessing": true,
            "sAjaxSource": $url + 'employees/get',
            "aoColumns": [
                {
                    "mData": "coordinator_id",
                    "mRender": function(data, type, full) {
                        return '<input type="checkbox" class="item-emp-checkbox emp-id" value="' + data + '" />';
                    }
                },
                {
                    "mData": "name",
                    "mRender": function(data, type, full) {
                        return '<a href="#view-emp-popup" class="btn-view-emp text-emp-name" data-toggle="modal" data-backdrop="static" data-keyboard="false">' + data + '</a>';
                    }
                },
                {
                    "mData": "coord_gender",
                    "mRender": function(data, type, full) {
                        if (data == '0') {
                            return 'Male';
                        } else {
                            return 'Female';
                        }
                    }
                },
                {"mData": "coord_address"},
                {"mData": "coord_email"},
                {"mData": "coord_num"},
                {"mData": "emp_date"},
            ],
            "aoColumnDefs": [{
                    "bSortable": false,
                    "aTargets": [0]}],
        });
    }
    // Clients functions--------------------------------------------------------
    // get client
    function get_client(clientId) {
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'client/view/' + clientId,
            type: 'post',
            dataType: 'json',
            success: function(data) {
                if (data != false) {
                    $('#view-client-popup #client-id').val(data.client_id);
                    $('#view-client-popup .view-client-container .name').text(data.client_lname + ' ' + data.client_fname);
                    $('#view-client-popup .view-client-container .address').text(data.client_address);
                    $('#view-client-popup .view-client-container .email').text(data.client_email);
                    $('#view-client-popup .view-client-container .contact').text(data.client_num);
                    $('#view-client-popup .edit-client-container .lname').val(data.client_lname);
                    $('#view-client-popup .edit-client-container .fname').val(data.client_fname);
                    var address = data.client_address.split(';');
                    var email = data.client_email.split(';');
                    var contact = data.client_num.split(';');
                    $('#view-client-popup .edit-client-container .address-1').val(address[0]);
                    $('#view-client-popup .edit-client-container .address-2').val(address[1]);
                    $('#view-client-popup .edit-client-container .address-3').val(address[2]);
                    $('#view-client-popup .edit-client-container .email-1').val(email[0]);
                    $('#view-client-popup .edit-client-container .email-2').val(email[1]);
                    $('#view-client-popup .edit-client-container .contact-no-1').val(contact[0]);
                    $('#view-client-popup .edit-client-container .contact-no-2').val(contact[1]);
                    $('#view-client-popup .edit-client-container .contact-no-3').val(contact[2]);
                    $('.loading-container').addClass('hide');
                } else {
                    $('#view-client-popup').modal('hide');
                    $('.alert-danger').remove();
                    $('.alert-success').remove();
                    $('.contacts-container').prepend('<div class="alert alert-danger margin-top">Something went wrong while fetching the client information. Please try again later.</div>');
                    error_msg();
                    $('.loading-container').addClass('hide');
                }
            },
            error: function() {
                $('#view-client-popup').modal('hide');
                $('.alert-danger').remove();
                $('.alert-success').remove();
                $('.contacts-container').prepend('<div class="alert alert-danger margin-top">Something went wrong while fetching the client information. Please try again later.</div>');
                error_msg();
                $('.loading-container').addClass('hide');
            }
        });
    }
    // save client
    function save_client(client, trigger) {
        var item = trigger.split('-');
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'client/save',
            type: 'post',
            data: client,
            dataType: 'json',
            success: function(data) {
                if (data.status === 'success') {
                    if (item[0] === 'new') {
                        $('.alert-danger').remove();
                        $('.alert-success').remove();
                        $('.contacts-container').prepend('<div class="alert alert-success margin-top">' + data.msg + '</div>');
                        refresh_clients_table();
                        success_msg();
                        $('#' + trigger).modal('hide');
                    } else if (item[0] === 'view') {
                        $('.alert-danger').remove();
                        $('.alert-success').remove();
                        $('.contacts-container').prepend('<div class="alert alert-success margin-top">' + data.msg + '</div>');
                        refresh_clients_table();
                        success_msg();
                        $('#' + trigger).modal('hide');
                    } else if (trigger == 'e-d-new-client-popup') {
                        $('.alert').remove();
                        $('#event-details-tab .client-select').append('<option value="' + data.client.client_id + '">' +
                                data.client.client_lname + ', ' + data.client.client_fname + '</option>');
                        $('.create-event-container').prepend('<div class="alert alert-success margin-top">' + data.msg + '</div>');
                        success_msg();
                        $('#' + trigger).modal('hide');
                    } else if (trigger === 'view-event-details-tab') {
                        $('.alert-danger').remove();
                        $('.alert-success').remove();
                        $('.edit-event-details-container #client-form .client-select').append('<option value="' + data.client.client_id + '">' +
                                data.client.client_lname + ', ' + data.client.client_fname + '</option>');
                        $('.edit-event-details-container #client-form .lname').val('');
                        $('.edit-event-details-container #client-form .fname').val('');
                        $('.edit-event-details-container #client-form .address-text').val('');
                        $('.edit-event-details-container #client-form .email-text').val('');
                        $('.edit-event-details-container #client-form .contact-no-text').val('');
                        $('#view-event-details-tab .new-e-c-container').addClass('hide').siblings('.form-sep').remove();
                        $('#view-event-details-tab hr').after('<div class="alert alert-success margin-top">' + data.msg + '</div>');
                        success_msg();
                    }
                    $('.loading-container').addClass('hide');
                } else {
                    if (trigger == 'e-d-new-client-popup') {
                        if (data.client == 'already exist') {
                            $('.alert-danger').remove();
                            $('.alert-success').remove();
                            $('#e-d-new-client-popup #client-form').before('<div class="alert alert-danger">' + data.msg + '</div>');
                            error_msg();
                        } else {
                            $('.alert-danger').remove();
                            $('.alert-success').remove();
                            $('.create-event-container').prepend('<div class="alert alert-danger margin-top">' + data.msg + '</div>');
                            error_msg();
                            $('#' + trigger).modal('hide');
                        }
                    } else if (trigger === 'view-event-details-tab') {
                        if (data.client == 'already exist') {
                            $('.alert-danger').remove();
                            $('.alert-success').remove();
                            $('#view-event-details-tab hr').after('<div class="alert alert-danger margin-top">' + data.msg + '</div>');
                            error_msg();
                        } else {
                            $('.alert-danger').remove();
                            $('.alert-success').remove();
                            $('#view-event-details-tab hr').after('<div class="alert alert-danger margin-top">' + data.msg + '</div>');
                            error_msg();
                        }
                    } else {
                        if (data.client == 'already exist') {
                            $('.alert-danger').remove();
                            $('.alert-success').remove();
                            $('#new-client-popup #client-form').before('<div class="alert alert-danger">' + data.msg + '</div>');
                            error_msg();
                        } else {
                            $('.alert-danger').remove();
                            $('.alert-success').remove();
                            $('.contacts-container').prepend('<div class="alert alert-danger margin-top">' + data.msg + '</div>');
                            error_msg();
                            $('#' + trigger).modal('hide');
                        }
                    }
                    $('.loading-container').addClass('hide');
                }
            },
            error: function() {
                if (trigger == 'e-d-new-client-popup') {
                    $('.alert-danger').remove();
                    $('.alert-success').remove();
                    $('.create-event-container').prepend('<div class="alert alert-danger margin-top">Something went wrong while performing changes to the client. Please try again later.</div>');
                    error_msg();
                    $('#' + trigger).modal('hide');
                } else if (trigger === 'view-event-details-tab') {
                    $('.alert-danger').remove();
                    $('.alert-success').remove();
                    $('#view-event-details-tab hr').after('<div class="alert alert-success margin-top">Something went wrong while performing changes to the client. Please try again later.</div>');
                    success_msg();
                } else {
                    $('.alert-danger').remove();
                    $('.alert-success').remove();
                    $('.contacts-container').prepend('<div class="alert alert-danger margin-top">Something went wrong while performing changes to the client. Please try again later.</div>');
                    error_msg();
                    $('#' + trigger).modal('hide');
                }
                $('.loading-container').addClass('hide');
            }
        });
    }
    // repopulate clients table
    function refresh_clients_table() {
        $('#clients-table').dataTable({
            "bDestroy": true,
            "bProcessing": true,
            "sAjaxSource": $url + 'clients/get',
            "aoColumns": [
                {
                    "mData": "client_id",
                    "mRender": function(data, type, full) {
                        return '<input type="checkbox" class="item-client-checkbox client-id" value="' + data + '" />';
                    }
                },
                {
                    "mData": "name",
                    "mRender": function(data, type, full) {
                        return '<a href="#view-client-popup" class="btn-view-client" data-toggle="modal" data-backdrop="static" data-keyboard="false">' + data + '</a>';
                    }
                },
                {"mData": "client_address"},
                {"mData": "client_email"},
                {"mData": "client_num"},
            ],
            "aoColumnDefs": [{
                    "bSortable": false,
                    "aTargets": [0]}],
        });
    }
    // Supplier functions-------------------------------------------------------
    // get supplier
    function get_supplier(supplierId) {
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'supplier/view/' + supplierId,
            type: 'post',
            dataType: 'json',
            success: function(data) {
                if (data != false) {
                    $('#view-supplier-popup #supplier-id').val(data.supplier_id);
                    $('#view-supplier-popup .view-supplier-container .cname').text(data.company);
                    $('#view-supplier-popup .view-supplier-container .contact-person').text(data.contact_person);
                    $('#view-supplier-popup .view-supplier-container .services').text(data.services);
                    $('#view-supplier-popup .view-supplier-container .address').text(data.s_address);
                    $('#view-supplier-popup .view-supplier-container .email').text(data.s_email);
                    $('#view-supplier-popup .view-supplier-container .contact').text(data.s_num);
                    $('#view-supplier-popup .edit-supplier-container .cname').val(data.company);
                    $('#view-supplier-popup .edit-supplier-container .contact-person').val(data.contact_person);
                    var services = data.services.split(';');
                    var address = data.s_address.split(';');
                    var email = data.s_email.split(';');
                    var contact = data.s_num.split(';');
                    for (var i = 0; i < services.length; i++) {
                        $('#view-supplier-popup .edit-supplier-container .another-services').after('<input type="text" value="' + services[i]
                                + '" class="form-control services-text d-services" name="address">');
                    }
                    $('#view-supplier-popup .edit-supplier-container .address-1').val(address[0]);
                    $('#view-supplier-popup .edit-supplier-container .address-2').val(address[1]);
                    $('#view-supplier-popup .edit-supplier-container .address-3').val(address[2]);
                    $('#view-supplier-popup .edit-supplier-container .email-1').val(email[0]);
                    $('#view-supplier-popup .edit-supplier-container .email-2').val(email[1]);
                    $('#view-supplier-popup .edit-supplier-container .contact-no-1').val(contact[0]);
                    $('#view-supplier-popup .edit-supplier-container .contact-no-2').val(contact[1]);
                    $('#view-supplier-popup .edit-supplier-container .contact-no-3').val(contact[2]);
                    $('.loading-container').addClass('hide');
                } else {
                    $('#view-supplier-popup').modal('hide');
                    $('.alert-danger').remove();
                    $('.alert-success').remove();
                    $('.contacts-container').prepend('<div class="alert alert-danger margin-top">Something went wrong while fetching the supplier information. Please try again later.</div>');
                    error_msg();
                    $('.loading-container').addClass('hide');
                }
            },
            error: function() {
                $('#view-supplier-popup').modal('hide');
                $('.alert-danger').remove();
                $('.alert-success').remove();
                $('.contacts-container').prepend('<div class="alert alert-danger margin-top">Something went wrong while fetching the supplier information. Please try again later.</div>');
                error_msg();
                $('.loading-container').addClass('hide');
            }
        });
    }
    // save supplier
    function save_supplier(supplier, trigger) {
        var item = trigger.split('-');
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'supplier/save',
            type: 'post',
            data: supplier,
            dataType: 'json',
            success: function(data) {
                if (data.status === 'success') {
                    if (item[0] === 'new') {
                        $('.alert-danger').remove();
                        $('.alert-success').remove();
                        $('.contacts-container').prepend('<div class="alert alert-success margin-top">' + data.msg + '</div>');
                        refresh_supplier_table();
                        success_msg();
                        $('#' + trigger).modal('hide');
                    } else if (item[0] === 'view') {
                        $('.alert-danger').remove();
                        $('.alert-success').remove();
                        $('.contacts-container').prepend('<div class="alert alert-success margin-top">' + data.msg + '</div>');
                        refresh_supplier_table();
                        success_msg();
                        $('#' + trigger).modal('hide');
                    } else if (trigger == 'e-s-new-supplier-popup') {
                        $('.alert-danger').remove();
                        $('.alert-success').remove();
                        $('#event-supplier-tab #event-supplier-list').
                                prepend('<div class="list-group" style="padding:1em;border: solid 1px #cccccc;">' +
                                '<h4 class="list-group-item-heading">Company Name: ' + data.supplier.company + '</h4>' +
                                '<p class="list-group-item-text">Contact Person: ' + data.supplier.contact_person + '</p>' +
                                '<p class="list-group-item-text">Available Services: <span class="available-services">' + data.supplier.services + '</span></p>' +
                                '<p class="list-group-item-text">Services chosen: <span class="services-chosen"></span></p>' +
                                '<div class="btn-group pull-right">' +
                                '<a href="#services-popup" data-toggle="modal" data-backdrop="static" data-keyboard="false" class="btn-assign-services" data-supplierid="' + data.supplier.supplier_id + '">Services</a>' +
                                '</div>' +
                                '<div class="clearfix"></div>' +
                                '</div>');
                        $('.create-event-container').prepend('<div class="alert alert-success margin-top">' + data.msg + '</div>');
                        success_msg();
                        $('#' + trigger).modal('hide');
                    }
                    $('.loading-container').addClass('hide');
                } else {
                    if (trigger == 'e-s-new-supplier-popup') {
                        if (data.supplier == 'already exist') {
                            $('.alert-danger').remove();
                            $('.alert-success').remove();
                            $('#e-s-new-supplier-popup #supplier-form').before('<div class="alert alert-danger">' + data.msg + '</div>');
                            error_msg();
                        } else {
                            $('.alert-danger').remove();
                            $('.alert-success').remove();
                            $('.create-event-container').prepend('<div class="alert alert-danger margin-top">' + data.msg + '</div>');
                            error_msg();
                            $('#' + trigger).modal('hide');
                        }
                    } else {
                        if (data.supplier == 'already exist') {
                            $('.alert-danger').remove();
                            $('.alert-success').remove();
                            $('#new-supplier-popup #supplier-form').before('<div class="alert alert-danger">' + data.msg + '</div>');
                            error_msg();
                        } else {
                            $('.alert-danger').remove();
                            $('.alert-success').remove();
                            $('.contacts-container').prepend('<div class="alert alert-danger margin-top">' + data.msg + '</div>');
                            error_msg();
                            $('#' + trigger).modal('hide');
                        }
                    }
                    $('.loading-container').addClass('hide');
                }
            },
            error: function() {
                $('.alert-danger').remove();
                $('.alert-success').remove();
                $('.contacts-container').prepend('<div class="alert alert-danger margin-top">Something went wrong while performing changes to the supplier. Please try again later.</div>');
                error_msg();
                $('#' + trigger).modal('hide');
                $('.loading-container').addClass('hide');
            }
        });
    }
    // repopulate supplier table
    function refresh_supplier_table() {
        $('#supplier-table').dataTable({
            "bDestroy": true,
            "bProcessing": true,
            "sAjaxSource": $url + 'supplier/get',
            "aoColumns": [
                {
                    "mData": "supplier_id",
                    "mRender": function(data, type, full) {
                        return '<input type="checkbox" class="item-supplier-checkbox supplier-id" value="' + data + '" />';
                    }
                },
                {
                    "mData": "company",
                    "mRender": function(data, type, full) {
                        return '<a href="#view-supplier-popup" class="btn-view-supplier" data-toggle="modal" data-backdrop="static" data-keyboard="false">' + data + '</a>';
                    }
                },
                {"mData": "contact_person"},
                {"mData": "services"},
                {"mData": "s_address"},
                {"mData": "s_email"},
                {"mData": "s_num"},
            ],
            "aoColumnDefs": [{
                    "bSortable": false,
                    "aTargets": [0]}],
        });
    }
    // Manage Resource
    // Files functions----------------------------------------------------------
    // repopulate the files table
    function refresh_files_table() {
        $('#files-table').dataTable({
            "bDestroy": true,
            "bProcessing": true,
            "sAjaxSource": $url + 'files/get',
            "aoColumns": [
                {
                    "mData": "file_id",
                    "mRender": function(data, type, full) {
                        return '<input type="checkbox" class="item-file-checkbox" value="' + data + '" />';
                    }
                },
                {"mDataProp": "file_name"},
                {
                    "mDataProp": "file_type",
                    "mRender": function(data, type, full) {
                        if (data == '0') {
                            return 'Document';
                        } else if (data == '1') {
                            return 'Report';
                        }
                    }
                },
                {"mDataProp": "date_uploaded"},
                {
                    "mDataProp": "file_path",
                    "mRender": function(data, type, full) {
                        return '<a href="' + $url + data + '" class="btn btn-primary btn-xs" role="button" target="_blank" title="Download">' +
                                '<span class="glyphicon glyphicon-download"></span></a>';
                    }
                }
            ],
            "aoColumnDefs": [{
                    "bSortable": false,
                    "aTargets": [0, 4]}],
        });
    }
    // Venues functions---------------------------------------------------------
    //save venue
    function save_venue(venue, trigger) {
        var item = trigger.split('-');
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'venue/save',
            type: 'post',
            dataType: 'json',
            data: venue,
            success: function(data) {
                if (data.status !== 'error') {
                    if (item[0] === 'new') {
                        $('#' + trigger).modal('hide');
                        $('.alert-success').remove();
                        $('.alert-danger').remove();
                        $('.resource-container').prepend('<div class="alert alert-success margin-top">' + data.msg + '</div>');
                        refresh_venues_table();
                        success_msg();
                    } else if (item[0] === 'edit') {
                        $('#' + trigger).modal('hide');
                        $('.alert-success').remove();
                        $('.resource-container').prepend('<div class="alert alert-success margin-top">' + data.msg + '</div>');
                        refresh_venues_table();
                        success_msg();
                    } else if (trigger == 'e-d-new-venue-popup') {
                        $('#' + trigger).modal('hide');
                        $('.alert-success').remove();
                        $('.alert-danger').remove();
                        $('#event-details-tab .venue-panel').append('<label><input type="checkbox" class="venue-checkbox" value="' + data.venue.venue_id + '" /> ' + data.venue.venue_name + '</label>&nbsp;');
                        $('.create-event-container').prepend('<div class="alert alert-success margin-top">' + data.msg + '</div>');
                        success_msg();
                    } else if (trigger === 'view-event-details-tab') {
                        $('.alert').remove();
                        $('.edit-event-details-container .all-venues .default-venue').
                                after('<option value="'+data.venue.venue_id+'">' + data.venue.venue_name +' ('+data.venue.venue_address +')</option>');
                        $('.edit-event-details-container #emp-form .venue-name').val('');
                        $('.edit-event-details-container #emp-form .venue-address').val('');
                        $('#view-event-details-tab .new-e-v-container').addClass('hide').siblings('.form-sep').remove();
                        $('#view-event-details-tab hr').after('<div class="alert alert-success margin-top">' + data.msg + '</div>');
                        success_msg();
                    }
                    $('.loading-container').addClass('hide');
                } else {
                    if (trigger == 'e-d-new-venue-popup') {
                        if (data.venue == 'already exist') {
                            $('.alert-success').remove();
                            $('.alert-danger').remove();
                            $('#e-d-new-venue-popup #venue-form').before('<div class="alert alert-danger">' + data.msg + '</div>');
                            error_msg();
                        } else {
                            $('#e-d-new-venue-popup').modal('hide');
                            $('.alert-success').remove();
                            $('.alert-danger').remove();
                            $('.create-event-container').prepend('<div class="alert alert-danger margin-top">' + data.msg + '</div>');
                            error_msg();
                        }
                    } else if (trigger === 'view-event-details-tab') {
                        if (data.emp === 'already exist') {
                            $('.alert-danger').remove();
                            $('.alert-success').remove();
                            $('#view-event-details-tab hr').after('<div class="alert alert-danger margin-top">' + data.msg + '</div>');
                            error_msg();
                        } else {
                            $('.alert-danger').remove();
                            $('.alert-success').remove();
                            $('#view-event-details-tab hr').after('<div class="alert alert-danger margin-top">' + data.msg + '</div>');
                            error_msg();
                        }
                    } else {
                        if (data.venue == 'already exist') {
                            $('.alert-success').remove();
                            $('.alert-danger').remove();
                            $('#new-venue-popup #venue-form').before('<div class="alert alert-danger">' + data.msg + '</div>');
                            error_msg();
                        } else {
                            $('#' + trigger).modal('hide');
                            $('.alert-success').remove();
                            $('.alert-danger').remove();
                            $('.resource-container').prepend('<div class="alert alert-danger margin-top">' + data.msg + '</div>');
                            erorr_msg();
                        }
                    }
                    $('.loading-container').addClass('hide');
                }
            },
            error: function() {
                if (trigger == 'e-d-new-venue-popup') {
                    $('#e-d-new-venue-popup').modal('hide');
                    $('.alert-success').remove();
                    $('.alert-danger').remove();
                    $('.create-event-container').prepend('<div class="alert alert-danger margin-top">Something went wrong while saving venue. Please try again later.</div>');
                    error_msg();
                } else if (trigger === 'view-event-details-tab') {
                    $('.alert-danger').remove();
                    $('.alert-success').remove();
                    $('#view-event-details-tab hr').after('<div class="alert alert-danger margin-top">Something went wrong while saving venue. Please try again later.</div>');
                    error_msg();
                } else {
                    $('#' + trigger).modal('hide');
                    $('.alert-success').remove();
                    $('.alert-danger').remove();
                    $('.resource-container').prepend('<div class="alert alert-danger margin-top">Something went wrong while saving venue. Please try again later.</div>');
                    error_msg();
                }
                $('.loading-container').addClass('hide');
            }
        });
    }
    // repopulate venues table
    function refresh_venues_table() {
        $('#venues-table').dataTable({
            "bDestroy": true,
            "bProcessing": true,
            "sAjaxSource": $url + 'venues/get',
            "aoColumns": [
                {
                    "mData": "venue_id",
                    "mRender": function(data, type, full) {
                        return '<input type="checkbox" class="item-venue-checkbox" value="' + data + '" />';
                    }
                },
                {"mData": "venue_name"},
                {"mData": "venue_address"},
            ],
            "aoColumnDefs": [{
                    "bSortable": false,
                    "aTargets": [0]}],
        });
    }
    // Event Types functions----------------------------------------------------
    // repopulate event types table
    function refresh_event_types_table() {
        $('#event-types-table').dataTable({
            "bDestroy": true,
            "bProcessing": true,
            "sAjaxSource": $url + 'event-types/get',
            "aoColumns": [
                {
                    "mData": "type_id",
                    "mRender": function(data, type, full) {
                        return '<input type="checkbox" class="item-event-type-checkbox venue-id" value="' + data + '" />';
                    }
                },
                {"mData": "type_name"},
            ],
            "aoColumnDefs": [{
                    "bSortable": false,
                    "aTargets": [0]}],
        });
    }
    // Messages-----------------------------------------------------------------
    // Inbox functions----------------------------------------------------------
    // get message
    function get_inbox_msg(msg_id) {
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'message/inbox/' + msg_id,
            type: 'post',
            dataType: 'json',
            success: function(data) {
                // view message
                $('#view-inbox-msg-popup .view-container .msg-sender').val(data.coord_lname + ', ' + data.coord_fname);
                $('#view-inbox-msg-popup .view-container .msg-sender').attr('data-senderid', data.coordinator_id);
                $('#view-inbox-msg-popup .view-container .msg-subject').val(data.subject);
                $('#view-inbox-msg-popup .view-container .msg-body').val(data.msg_body);
                if (data.attach_name != '') {
                    $('#view-inbox-msg-popup .view-container .attachment-file').attr('href', $url + data.attach_path).attr('target', '_blank');
                    $('#view-inbox-msg-popup .view-container .attachment-file').text(data.attach_name);
                } else {
                    $('#view-inbox-msg-popup .view-container .attachment-file').attr('href', '#').removeAttr('target');
                    $('#view-inbox-msg-popup .view-container .attachment-file').text('No attachment');
                }
                // reply message
                $('#view-inbox-msg-popup .reply-container .msg-recipient').val(data.coord_lname + ', ' + data.coord_fname);
                $('#view-inbox-msg-popup .reply-container .msg-recipient').attr('data-recipientid', data.coordinator_id);
                // forward message
                $('#view-inbox-msg-popup .forward-container .msg-subject').val(data.subject);
                $('#view-inbox-msg-popup .forward-container .msg-body').val(data.msg_body);
                if (data.attach_name != '') {
                    $('#view-inbox-msg-popup .forward-container .attachment-file').attr('href', $url + data.attach_path)
                            .attr('target', '_blank').attr('data-attachpath', data.attach_path);
                    $('#view-inbox-msg-popup .forward-container .attachment-file').text(data.attach_name);
                } else {
                    $('#view-inbox-msg-popup .view-container .attachment-file').attr('href', '#').removeAttr('target');
                    $('#view-inbox-msg-popup .forward-container .attachment-file').text('No attachment');
                }
                $('.loading-container').addClass('hide');
            },
            error: function() {
                $('#view-inbox-msg-popup').modal('hide');
                $('.alert-success').remove();
                $('.alert-danger').remove();
                $('.messages-container').prepend('<div class="alert alert-danger margin-top">Something went wrong while fetching inbox message. Please try again later.</div>');
                error_msg();
                $('.loading-container').addClass('hide');
            },
        });
    }
    // repopulate venues table
    function refresh_inbox_table() {
        $('#inbox-table').dataTable({
            "bDestroy": true,
            "bProcessing": true,
            "sAjaxSource": $url + 'messages/get/inbox',
            "aoColumns": [
                {
                    "mData": "msg_id",
                    "mRender": function(data, type, full) {
                        return '<input type="checkbox" class="item-inbox-checkbox" value="' + data + '" />';
                    }
                },
                {"mData": "name"},
                {
                    "mData": "subject",
                    "mRender": function(data, type, full) {
                        return '<a class="btn-view-inbox-msg" data-toggle="modal"' +
                                'href="#view-inbox-msg-popup">' + data + '</a>';
                    }
                },
                {"mData": "date"},
            ],
            "aoColumnDefs": [{
                    "bSortable": false,
                    "aTargets": [0]}],
        });
    }
    function get_sentbox_msg(msg_id) {
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'message/sentbox/' + msg_id,
            type: 'post',
            dataType: 'json',
            success: function(data) {
                // view message
                $('#view-sentbox-msg-popup .view-container .msg-sender').val(data.coord_lname + ', ' + data.coord_fname);
                $('#view-sentbox-msg-popup .view-container .msg-sender').attr('data-senderid', data.coordinator_id);
                $('#view-sentbox-msg-popup .view-container .msg-subject').val(data.subject);
                $('#view-sentbox-msg-popup .view-container .msg-body').val(data.msg_body);
                if (data.attach_name != '') {
                    $('#view-sentbox-msg-popup .view-container .attachment-file').attr('href', $url + data.attach_path).attr('target', '_blank');
                    $('#view-sentbox-msg-popup .view-container .attachment-file').text(data.attach_name);
                } else {
                    $('#view-sentbox-msg-popup .view-container .attachment-file').attr('href', '#').removeAttr('target');
                    $('#view-sentbox-msg-popup .view-container .attachment-file').text('No attachment');
                }
                // reply message
                $('#view-sentbox-msg-popup .reply-container .msg-recipient').val(data.coord_lname + ', ' + data.coord_fname);
                $('#view-sentbox-msg-popup .reply-container .msg-recipient').attr('data-recipientid', data.coordinator_id);
                // forward message
                $('#view-sentbox-msg-popup .forward-container .msg-subject').val(data.subject);
                $('#view-sentbox-msg-popup .forward-container .msg-body').val(data.msg_body);
                if (data.attach_name != '') {
                    $('#view-sentbox-msg-popup .forward-container .attachment-file').attr('href', $url + data.attach_path)
                            .attr('target', '_blank').attr('data-attachpath', data.attach_path);
                    $('#view-sentbox-msg-popup .forward-container .attachment-file').text(data.attach_name);
                } else {
                    $('#view-sentbox-msg-popup .view-container .attachment-file').attr('href', '#').removeAttr('target');
                    $('#view-sentbox-msg-popup .forward-container .attachment-file').text('No attachment');
                }
                $('.loading-container').addClass('hide');
            },
            error: function() {
                $('#view-sentbox-msg-popup').modal('hide');
                $('.alert-success').remove();
                $('.alert-danger').remove();
                $('.messages-container').prepend('<div class="alert alert-danger margin-top">Something went wrong while fetching sentbox message Please try again later.</div>');
                error_msg();
                $('.loading-container').addClass('hide');
            },
        });
    }
    // repopulate sentbox table
    function refresh_sentbox_table() {
        $('#sentbox-table').dataTable({
            "bDestroy": true,
            "bProcessing": true,
            "sAjaxSource": $url + 'messages/get/sentbox',
            "aoColumns": [
                {
                    "mData": "msg_id",
                    "mRender": function(data, type, full) {
                        return '<input type="checkbox" class="item-sentbox-checkbox" value="' + data + '" />';
                    }
                },
                {"mData": "name"},
                {
                    "mData": "subject",
                    "mRender": function(data, type, full) {
                        return '<a class="btn-view-sentbox-msg" data-toggle="modal"' +
                                'href="#view-sentbox-msg-popup">' + data + '</a>';
                    }
                },
                {"mData": "date"},
            ],
            "aoColumnDefs": [{
                    "bSortable": false,
                    "aTargets": [0]}],
        });
    }
//    // get draft messages
//    function get_draft_msg(msg_id){
//         $.ajax({
//            url: $url + 'message/draft/'+msg_id,
//            type: 'post',
//            dataType: 'json',
//            success: function(data) {
//                $('#view-draft-msg-popup .msg-subject').val(data.subject);
//                $('#view-draft-msg-popup .msg-body').val(data.msg_body);
//            },
//            error: function(){
//                alert('error');
//            },
//        });
//    }
//    // repopulate draft table
//    function refresh_draft_table(){
//        $('#draft-table').dataTable({
//            "bDestroy": true,
//            "bProcessing": true,
//            "sAjaxSource": $url + 'messages/get/draft',
//            "aoColumns": [
//                { 
//                    "mData": "msg_id",
//                    "mRender": function ( data, type, full ) {
//                      return '<input type="checkbox" class="item-draft-checkbox" value="'+data+'" />';
//                    }
//                },
//                {"mData": "name"},
//                { 
//                    "mData": "subject",
//                    "mRender": function ( data, type, full ) {
//                      return '<a class="btn-view-draft-msg" data-toggle="modal"'+
//                            'href="#view-draft-msg-popup">'+data+'</a>';
//                    } 
//                },
//            ],
//            "aoColumnDefs":[{
//                "bSortable": false, 
//                "aTargets":[0]}],
//        });
//    }

    // send default message
    function send_default_msg(trigger, msg) {
        $('.loading-container').removeClass('hide');
        $.ajax({
            url: $url + 'message/send-message',
            type: 'post',
            data: msg,
            dataType: 'json',
            success: function(data) {
                if (data.status === 'success') {
                    $('#' + trigger).modal('hide');
                    $('.alert-danger').remove();
                    $('.alert-success').remove();
                    $('.messages-container').prepend('<div class="alert alert-success margin-top">' + data.msg + '</div>');
                    if (msg.action == 1) {
                        refresh_draft_table();
                    } else {
                        refresh_sentbox_table();
                    }
                    success_msg();
                    $('.loading-container').addClass('hide');
                } else {
                    $('#' + trigger).modal('hide');
                    $('.alert-danger').remove();
                    $('.alert-success').remove();
                    $('.messages-container').prepend('<div class="alert alert-danger margin-top">' + data.msg + '</div>');
                    error_msg();
                    $('.loading-container').addClass('hide');
                }
            },
            error: function() {
                $('#' + trigger).modal('hide');
                $('.alert-danger').remove();
                $('.alert-success').remove();
                $('.messages-container').prepend('<div class="alert alert-danger margin-top">Something went wrong while sending message. Please try again later.</div>');
                error_msg();
                $('.loading-container').addClass('hide');
            }
        });
    }
    // send message with attachment
    function send_attachment_msg(trigger, msg, userfile) {
        var item = trigger.split('-');
        $('.loading-container').removeClass('hide');
        $.ajaxFileUpload({
            url: $url + 'message/send-message',
            type: 'post',
            data: msg,
            fileElementId: userfile,
            dataType: 'json',
            success: function(data) {
                if (data.status === 'success') {
                    $('.alert-danger').remove();
                    $('.alert-success').remove();
                    $('.messages-container').prepend('<div class="alert alert-success margin-top">' + data.msg + '</div>');
                    $('#' + trigger).modal('hide');
                    if (msg.action == 1) {
                        refresh_draft_table();
                    } else {
                        refresh_sentbox_table();
                    }
                    success_msg();
                    $('.loading-container').addClass('hide');
                } else {
                    $('#view-' + item[1] + '-msg-popup div').find('.alert-danger').remove();
                    $('#view-' + item[1] + '-msg-popup .msg-id').before('<div class="alert alert-danger margin-top">' + data.msg + '</div>');
                    $('.loading-container').addClass('hide');
                }
            },
            error: function() {
                $('#' + trigger).modal('hide');
                $('.alert-danger').remove();
                $('.alert-success').remove();
                $('.messages-container').prepend('<div class="alert alert-danger margin-top">Something went wrong while sending message. Please try again later.</div>');
                error_msg();
                $('.loading-container').addClass('hide');
            }
        });
    }
    // General functions--------------------------------------------------------
    // generate the time and date with a specific format
    function date_time() {
        var date = new Date();
        var yr = date.getFullYear();
        var day = date.getDay();
        var mon = date.getMonth() + 1;
        var hr = date.getHours();
        var min = date.getMinutes();
        var sec = date.getSeconds();
        return yr + '-' + day + '-' + mon + ' ' + hr + ':' + min + ':' + sec;
    }
    // add a new services row
    function new_services_row(trigger, target) {
        $('#' + trigger + ' ' + ' .' + target + ' .services-container').
                append('<div class="input-group">' +
                '<input type="text" class="form-control services-text services-d" name="address">' +
                '<span class="input-group-btn">' +
                '<button class="btn btn-default btn-remove-services" type="button"><span class="glyphicon glyphicon-remove"></span></button>' +
                '</span></div>');
    }
    // add a new address row
    function new_address_row(trigger, target) {
        $('#' + trigger + ' ' + ' .' + target + ' .address-container').
                append('<div class="input-group">' +
                '<input type="text" class="form-control address-text d-address" name="address">' +
                '<span class="input-group-btn">' +
                '<button class="btn btn-default btn-remove-address" type="button"><span class="glyphicon glyphicon-remove"></span></button>' +
                '</span></div>');
    }
    // add a email row
    function new_email_row(trigger, target) {
        $('#' + trigger + ' ' + ' .' + target + ' .email-container').
                append('<div class="input-group">' +
                '<input type="text" class="form-control email-text d-email" name="email">' +
                '<span class="input-group-btn">' +
                '<button class="btn btn-default btn-remove-email" type="button"><span class="glyphicon glyphicon-remove"></span></button>' +
                '</span></div>');
    }
    ;
    // add a new contact no. row
    function new_contact_row(trigger, target) {
        $('#' + trigger + ' ' + ' .' + target + ' .contact-no-container').
                append('<div class="input-group">' +
                '<input type="text" class="form-control contact-no-text d-contact-no" name="email">' +
                '<span class="input-group-btn">' +
                '<button class="btn btn-default btn-remove-contact-no" type="button"><span class="glyphicon glyphicon-remove"></span></button>' +
                '</span></div>');
    }
    ;
    // remove success message after 5sec
    function success_msg() {
        setTimeout(function() {
            $('.alert-success').fadeOut('slow', function() {
                $(this).remove();
            });
            $('.success-msg').fadeOut('slow', function() {
                $(this).remove();
            });
        }, 5000);
    }
    // remove success message after 5sec
    function error_msg() {
        setTimeout(function() {
            $('.alert-danger').fadeOut('slow', function() {
                $(this).remove();
            });
            $('.required-error').fadeOut('slow', function() {
                $(this).remove();
            });
        }, 5000);
    }
    // remove alerts
    function remove_alert(){
        setTimeout(function() {
            $('.alert').fadeOut('slow', function() {
                $(this).remove();
            });
        }, 5000);
    }
    //Event Organizer
    $("#create-event-btn").on("click", function() {
        $("#create-event-detail-menu").show();
        $("#create-event-details-tab").show();
        $("#create-event-supplier-tab").hide();
        $("#create-event-checklist-tab").hide();
        $("#create-coord-task-tab").hide();
        $("#list-view").hide();
        $("#cal-view").hide();

        $("#view-event-detail-menu").hide();
        $("#view-event-details-tab").hide();
        $("#view-event-supplier-tab").hide();
        $("#view-event-checklist-tab").hide();
        $("#view-coord-task-tab").hide();
    });

    $("#cal-view-btn").on("click", function() {
        $("#create-event-detail-menu").hide();
        $("#create-event-details-tab").hide();
        $("#create-event-supplier-tab").hide();
        $("#create-event-checklist-tab").hide();
        $("#create-coord-task-tab").hide();
        $("#list-view").hide();
        $("#cal-view").show();

        $("#view-event-detail-menu").hide();
        $("#view-event-details-tab").hide();
        $("#view-event-supplier-tab").hide();
        $("#view-event-checklist-tab").hide();
        $("#view-coord-task-tab").hide();
    });

    $("#list-view-btn").on("click", function() {
        $("#create-event-detail-menu").hide();
        $("#create-event-details-tab").hide();
        $("#create-event-supplier-tab").hide();
        $("#create-event-checklist-tab").hide();
        $("#create-coord-task-tab").hide();
        $("#list-view").show();
        $("#cal-view").hide();

        $("#view-event-detail-menu").hide();
        $("#view-event-details-tab").hide();
        $("#view-event-supplier-tab").hide();
        $("#view-event-checklist-tab").hide();
        $("#view-coord-task-tab").hide();
    });

    $("#event-btn").on("click", function() {
        $("#create-event-detail-menu").show();
        $("#create-event-details-tab").show();
        $("#create-event-supplier-tab").hide();
        $("#create-event-checklist-tab").hide();
        $("#create-coord-task-tab").hide();
        $("#list-view").hide();
        $("#cal-view").hide();

        $("#view-event-detail-menu").hide();
        $("#view-event-details-tab").hide();
        $("#view-event-supplier-tab").hide();
        $("#view-event-checklist-tab").hide();
        $("#view-coord-task-tab").hide();
    });

    $("#supplier-btn").on("click", function() {
        $("#create-event-detail-menu").show();
        $("#create-event-details-tab").hide();
        $("#create-event-supplier-tab").show();
        $("#create-event-checklist-tab").hide();
        $("#create-coord-task-tab").hide();
        $("#list-view").hide();
        $("#calv-view").hide();

        $("#view-event-detail-menu").hide();
        $("#view-event-details-tab").hide();
        $("#view-event-supplier-tab").hide();
        $("#view-event-checklist-tab").hide();
        $("#view-coord-task-tab").hide();
    });
    $("#checklist-btn").on("click", function() {
        $("#create-event-detail-menu").show();
        $("#create-event-details-tab").hide();
        $("#create-event-supplier-tab").hide();
        $("#create-event-checklist-tab").show();
        $("#create-coord-task-tab").hide();
        $("#list-view").hide();
        $("#cal-view").hide();

        $("#view-event-detail-menu").hide();
        $("#view-event-details-tab").hide();
        $("#view-event-supplier-tab").hide();
        $("#view-event-checklist-tab").hide();
        $("#view-coord-task-tab").hide();
    });
    $("#task-btn").on("click", function() {
        $("#create-event-detail-menu").show();
        $("#create-event-details-tab").hide();
        $("#create-event-supplier-tab").hide();
        $("#create-event-checklist-tab").hide();
        $("#create-coord-task-tab").show();
        $("#list-view").hide();
        $("#cal-view").hide();

        $("#view-event-detail-menu").hide();
        $("#view-event-details-tab").hide();
        $("#view-event-supplier-tab").hide();
        $("#view-event-checklist-tab").hide();
        $("#view-coord-task-tab").hide();
    });

    $("#event1").on("click", function() {
        $("#create-event-detail-menu").hide();
        $("#create-event-details-tab").hide();
        $("#create-event-supplier-tab").hide();
        $("#create-event-checklist-tab").hide();
        $("#create-coord-task-tab").hide();
        $("#list-view").hide();
        $("#cal-view").hide();

        $("#view-event-detail-menu").show();
        $("#view-event-details-tab").show();
        $("#view-event-supplier-tab").hide();
        $("#view-event-checklist-tab").hide();
        $("#view-coord-task-tab").hide();
    });

    $("#view-event-btn").on("click", function() {
        $("#create-event-detail-menu").hide();
        $("#create-event-details-tab").hide();
        $("#create-event-supplier-tab").hide();
        $("#create-event-checklist-tab").hide();
        $("#create-coord-task-tab").hide();
        $("#list-view").hide();
        $("#cal-view").hide();

        $("#view-event-detail-menu").show();
        $("#view-event-details-tab").show();
        $("#view-event-supplier-tab").hide();
        $("#view-event-checklist-tab").hide();
        $("#view-coord-task-tab").hide();
    });

    $("#view-supplier-btn").on("click", function() {
        $("#create-event-detail-menu").hide();
        $("#create-event-details-tab").hide();
        $("#create-event-supplier-tab").hide();
        $("#create-event-checklist-tab").hide();
        $("#create-coord-task-tab").hide();
        $("#list-view").hide();
        $("#calv-view").hide();

        $("#view-event-detail-menu").show();
        $("#view-event-details-tab").hide();
        $("#view-event-supplier-tab").show();
        $("#view-event-checklist-tab").hide();
        $("#view-coord-task-tab").hide();
    });
    $("#view-checklist-btn").on("click", function() {
        $("#create-event-detail-menu").hide();
        $("#create-event-details-tab").hide();
        $("#create-event-supplier-tab").hide();
        $("#create-event-checklist-tab").hide();
        $("#create-coord-task-tab").hide();
        $("#list-view").hide();
        $("#cal-view").hide();

        $("#view-event-detail-menu").show();
        $("#view-event-details-tab").hide();
        $("#view-event-supplier-tab").hide();
        $("#view-event-checklist-tab").show();
        $("#view-coord-task-tab").hide();
    });
    $("#view-task-btn").on("click", function() {
        $("#create-event-detail-menu").hide();
        $("#create-event-details-tab").hide();
        $("#create-event-supplier-tab").hide();
        $("#create-event-checklist-tab").hide();
        $("#create-coord-task-tab").hide();
        $("#list-view").hide();
        $("#cal-view").hide();

        $("#view-event-detail-menu").show();
        $("#view-event-details-tab").hide();
        $("#view-event-supplier-tab").hide();
        $("#view-event-checklist-tab").hide();
        $("#view-coord-task-tab").show();
    });


    /*-----------------Production Schedule----------------------*/
    tinymce.init({
        selector: ".textarea",
        plugins: "table",
        menubar: "tools table view insert edit",
        toolbar: "undo redo | styleselect | bold italic | bullist numlist outdent indent | table",
        height: "300"
    });

    function getEID() {
        return $('#view-event-calendar-popup #event-id').val();
    }

    $('#new-schedule-btn').on('click', function() {
        $('#new-schedule-form').removeClass('hide');
        $("#new-schedule-btn").addClass('hide');
    });

    $('#update-schedule-btn').on('click', function() {
        $('#edit-schedule-form').removeClass('hide');
        get_scheduleupdate(getEID());
    });

    $("#new-schedule-form .btn-save").on('click', function() {
        save_schedule(tinyMCE.get('description-area').getContent(), getEID());
    });

    $("#edit-schedule-form .btn-save").on('click', function() {
        update_schedule(tinyMCE.activeEditor.getContent(), getEID());
    });

    $(".schedule-nav").on('click', function() {
        $("#schedule-tab").removeClass("hide");
        $("#new-schedule-btn").addClass('hide');
        $("#update-schedule-btn").addClass('hide');
        $("#export-schedule-btn").addClass('hide');
        $("#pdf-schedule-btn").addClass('hide');
        get_schedule(getEID());
    });

    $("#modal-event-calendar li:not(:eq(5)) a").on('mousedown touchstart', function() {
        $("#schedule-tab").addClass('hide');
    });

    $("#edit-schedule-form .btn-cancel").on('click', function() {
        $("#edit-schedule-form").addClass('hide');
        $("#schedule-container").removeClass('hide');
        $("#update-schedule-btn").removeClass('hide');
        $("#export-schedule-btn").removeClass('hide');
        $("#pdf-schedule-btn").removeClass('hide');
    });

    $("#new-schedule-form .btn-cancel").on('click', function() {
        $("#new-schedule-form").addClass('hide');
        $("#new-schedule-btn").removeClass('hide');
    });

    $('#export-schedule-btn').on('click', function(e) {
        var a = document.createElement('a');
        var data_type = 'data:application/vnd.ms-excel';
        var table_div = document.getElementById('schedule-container');
        var table_html = table_div.outerHTML.replace(/ /g, '%20');
        a.href = data_type + ', ' + table_html;
        a.download = $('.view-event-from-calendar').text() + ' production schedule.xls';
        a.click();
        e.preventDefault();
    });

    $('#pdf-schedule-btn').on('click', function() {
        toPDF_schedule($('.view-event-from-calendar').text(), getEID());
    });

    function get_schedule(schedule) {
        $.ajax({
            url: $url + 'event/prodsched/view',
            type: 'post',
            data: {"schedule": schedule},
            dataType: 'json',
            success: function(data) {
                if (data.status !== 'error') {
                    $("#schedule-container").remove();
                    $("#schedule-tab").append("<div id =schedule-container>" + data.result + "</div>");
                    $("#schedule-container").removeClass('hide');
                    $("#update-schedule-btn").removeClass('hide');
                    $("#export-schedule-btn").removeClass('hide');
                    $("#pdf-schedule-btn").removeClass('hide');

                } else {
                    $("#schedule-container").append(data.result);
                    $("#schedule-container").removeClass('hide');
                    $("#new-schedule-btn").removeClass('hide');
                }
            }
        });
    }

    function get_scheduleupdate(schedule) {
        $.ajax({
            url: $url + 'event/prodsched/view',
            type: 'post',
            data: {"schedule": schedule},
            dataType: 'json',
            success: function(data) {
                if (data.status !== 'error') {
                    tinyMCE.get('description-update-area').setContent(data.result);
                    $("#schedule-container").addClass('hide');
                    $("#update-schedule-btn").addClass('hide');
                    $("#export-schedule-btn").addClass('hide');
                    $("#pdf-schedule-btn").addClass('hide');

                } else {
                    $("#schedule-container").append(data.result);
                    $("#schedule-container").removeClass('hide');
                    $("#new-schedule-btn").removeClass('hide');
                }
            }
        });
    }

    function save_schedule(prod, id) {
        $.ajax({
            url: $url + 'event/prodsched/save',
            type: 'post',
            data: {"descr": prod, "pid": id},
            dataType: 'json',
            success: function(data) {
                if (data.status !== 'error') {
                    $("#schedule-container").remove();
                    $("#schedule-tab").append("<div id =schedule-container>" + data.result + "</div>");
                    $("#schedule-container").removeClass('hide');
                    $("#update-schedule-btn").removeClass('hide');
                    $("#export-schedule-btn").removeClass('hide');
                    $("#pdf-schedule-btn").removeClass('hide');
                    $("#new-schedule-btn").addClass('hide');
                    $('#new-schedule-form').addClass('hide');
                } else {

                }
            },
            error: function() {
                alert('error');
            }
        });
    }

    function update_schedule(produ, id) {
        $.ajax({
            url: $url + 'event/prodsched/update',
            type: 'post',
            data: {"desc": produ, "id": id},
            dataType: 'json',
            success: function(data) {
                if (data.status !== 'error') {
                    $("#schedule-container").remove();
                    $("#schedule-tab").append("<div id =schedule-container>" + produ + "</div>");
                    $("#schedule-container").removeClass('hide');
                    $("#export-schedule-btn").removeClass('hide');
                    $("#pdf-schedule-btn").removeClass('hide');
                    $("#update-schedule-btn").removeClass('hide');
                    $('#edit-schedule-form').addClass('hide');
                } else {
                }
            },
            error: function() {
                alert('error');
            }
        });
    }

    function toPDF_schedule(name, id) {
        $.ajax({
            url: $url + 'event/prodsched/export',
            type: 'post',
            data: {"name": name, "pid": id},
            dataType: 'json',
            success: function(data) {
                if (data.status !== 'error') {
                    $("#toexportSched").remove();
                    $("#sched-export").append("<div id =toexportSched class=hide>" + data.result + "</div>");
                    exportToPDF_schedule();
                } else {

                }
            },
            error: function() {
                alert('error');
            }
        });
    }

    //not yet done 
    function exportToPDF_schedule() {
        var specialElementHandlers = {
            '#editor': function(element, renderer) {
                return true;
            }
        };

        var table = tableToJson($('#schedule-container table').get(0));
        var doc = new jsPDF('l', 'mm', 'a4', true);
        doc.cellInitialize();
        $.each(table, function(i, row) {
            $.each(row, function(j, cell) {
                doc.cell(10, 100, 100, 10, cell, i);
            });
        });
        doc.save($('.view-event-from-calendar').text() + ' production schedule.pdf');
    }

    function tableToJson(table) {
        var data = [];
        // first row needs to be headers
        var headers = [];
        for (var i = 0; i < table.rows[0].cells.length; i++) {
            headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi, '');
        }
        // go through cells
        for (var i = 0; i < table.rows.length; i++) {
            var tableRow = table.rows[i];
            var rowData = {};
            for (var j = 0; j < tableRow.cells.length; j++) {
                rowData[ headers[j] ] = tableRow.cells[j].innerHTML;
            }
            data.push(rowData);
        }
        return data;
    }


    /*-----------------guest dashboard----------------------*/
    $(".guest-nav li:eq(0)").on('mousedown touchstart', function() {
        $("#enter-details-con").addClass("hide");
        $("#choose-design-con").removeClass("hide");
        $("#invite-guests-con").addClass("hide");
        $("#finish-send-con").addClass("hide");
        $("#seatplan-con").addClass("hide");
    });
    $(".guest-nav li:eq(1)").on('mousedown touchstart', function() {
        $("#enter-details-con").removeClass("hide");
        $("#choose-design-con").addClass("hide");
        $("#invite-guests-con").addClass("hide");
        $("#finish-send-con").addClass("hide");
        $("#seatplan-con").addClass("hide");
    });
    $(".guest-nav li:eq(2)").on('mousedown touchstart', function() {
        $("#enter-details-con").addClass("hide");
        $("#choose-design-con").addClass("hide");
        $("#invite-guests-con").removeClass("hide");
        $("#finish-send-con").addClass("hide");
        $("#seatplan-con").addClass("hide");
    });
    $(".guest-nav li:eq(3)").on('mousedown touchstart', function() {
        $("#enter-details-con").addClass("hide");
        $("#choose-design-con").addClass("hide");
        $("#invite-guests-con").addClass("hide");
        $("#finish-send-con").removeClass("hide");
        $("#seatplan-con").addClass("hide");
    });
    $(".guest-nav li:eq(4)").on('mousedown touchstart', function() {
    });

    $(".design-pic").on('mousedown touchstart', function() {
        var imgurl = $(this).attr('src');
        $("#preview").css("background-image", "url('" + imgurl + "')");
    });


    /*------------------------guest-------------------------*/
    $("#modal-event-calendar li:eq(9) a").on('mousedown touchstart', function() {
        $("#guest-tab").removeClass("hide");
    });
    $("#modal-event-calendar li:not(:eq(9)) a").on('mousedown touchstart', function() {
        $("#guest-tab").addClass("hide");
    });

    $("#submit-guest-design").on("mousedown touchstart", function() {
        $("#design-type-id").val($('#view-event-calendar-popup #event-id').val());
        var formData = new FormData($("#img-design-form")[0]);
        var request = new XMLHttpRequest();
        request.open("POST", $url + "guest/upload-design");
        request.send(formData);

        $.ajax({
            url: $url + "guest/get-design-pics",
            type: "post",
            dataType: "json",
            success: function(data) {
                $("#collapseOne").text("");
                $("#collapseOne").append(data);
            }
        });
    });

    $(".pic").click(function() {
        var s = $(this).attr('src');
        $("#preview").css("background-image", "url('" + s + "')");
    });

    $("#nav-choose").on("mousedown touchstart", function() {
        $("#invite-guest-con").addClass("hide");
        $("#finish-and-send-con").addClass("hide");
        $("#choose-design-con").removeClass("hide");
    });

    $("#nav-invite").on("mousedown touchstart", function() {
        $("#invite-guest-con").removeClass("hide");
        $("#choose-design-con").addClass("hide");
        $("#finish-and-send-con").addClass("hide");
        refresh_guest_list_table();

    });

    $("#nav-finish").on("mousedown touchstart", function() {
        $("#invite-guest-con").addClass("hide");
        $("#choose-design-con").addClass("hide");
        $("#finish-and-send-con").removeClass("hide");
        $.ajax({
            url: $url + "guest/get-design-pics",
            type: "post",
            dataType: "json",
            success: function(data) {
                $("#collapseOne").text("");
                $("#collapseOne").append(data);
            }
        });
    });

    $("#finish-send").on('mousedown touchstart', function() {
        $.ajax({
            url: $url + "guest/send-invitation",
            type: "post",
            data: {"ev-id": $('#view-event-calendar-popup #event-id').val()},
            dataType: "json",
            success: function(data) {
                alert("na send na");
            }
        });
    });

    $('#save_guest').on('mousedown touchstart', function() {
        $.ajax({
            url: $url + 'guest/insert-guest',
            type: 'post',
            data: {'gname': $('#gname').val(), 'g_email': $('#g_email').val(), 'g_role': $('#g_role').val(), 'rsvp': $('#rsvp').val(), 'sent': $('#sent').val(), 'ev-id': $('#view-event-calendar-popup #event-id').val()},
            dataType: 'json',
            success: function(data) {
                if (data === 'success') {
                    refresh_guest_list_table();
                    $('#sent').val('');
                    $('#gname').val('');
                    $('#g_email').val('');
                    $('#g_role').val('');
                    $('#rsvp option[value=YES]').prop('selected', true);
                    $('#token option[value=YES]').prop('selected', true);
                }
            }
        });
    });

    $('#guest_table').dataTable({
        "aoColumnDefs": [{
                "bSortable": false,
                "aTargets": [0, 3, 4, 5, 7]}]
    });

    function refresh_guest_list_table() {
        $.ajax({
            url: $url + "guest/get-guests",
            type: "post",
            data: {'ev-id': $('#view-event-calendar-popup #event-id').val()},
            dataType: "json",
            success: function(res) {
                $('#guest_table').dataTable({
                    "bDestroy": true,
                    "bProcessing": true,
                    "aaData": res.aaData,
                    "aoColumns": [
                        {
                            "mData": "guest_id",
                            "mRender": function(data) {
                                return '<input type="checkbox" name="chk[]" name="chk" id="chk" class="chkbox" value="' + data + '" />';
                            }

                        },
                        {"mDataProp": "sent"},
                        {"mDataProp": "g_name"},
                        {"mDataProp": "g_email"},
                        {"mDataProp": "g_role"},
                        {"mDataProp": "rsvp"},
                        {"mDataProp": "token"},
                        {
                            "mDataProp": "guest_id",
                            "mRender": function(data, type, full) {
                                return '<button id="guest_edit_btn" name="edit_btn" title="Edit row" value="' + data + '" class="btn btn-info btn-xs edit_btn"><span class="glyphicon glyphicon-edit"></span></button>';
                            }
                        }
                    ],
                    "aoColumnDefs": [{
                            "bSortable": false,
                            "aTargets": [0, 3, 4, 5, 7]}]
                });

                $(".edit_btn").on('mousedown touchstart', function() {
                    if ($(this).children().hasClass('glyphicon-edit')) {
                        $(this).children().removeClass('glyphicon-edit').addClass('glyphicon-ok');
                        $(this).removeClass('btn-info').addClass('btn-success');

                        $(this).parent().parent().find('.edit_name').removeClass('hide');
                        $(this).parent().parent().find('.edit_gemail').removeClass('hide');
                        $(this).parent().parent().find('.edit_rsvp').removeClass('hide');
                        $(this).parent().parent().find('.edit_grole').removeClass('hide');
                        $(this).parent().parent().find('.edit_token').removeClass('hide');

                        $(this).parent().parent().find('.span_name').addClass('hide');
                        $(this).parent().parent().find('.span_gemail').addClass('hide');
                        $(this).parent().parent().find('.span_rsvp').addClass('hide');
                        $(this).parent().parent().find('.span_grole').addClass('hide');
                        $(this).parent().parent().find('.span_token').addClass('hide');

                    }
                    else {
                        $.ajax({
                            url: '/Guest/guest_management/update_guest',
                            type: 'POST',
                            data: {'guse_id': $('[name=guest_id]').val(), 'gname': $('[name=gname]').val(), 'g_email': $('[name=g_email]').val(), 'rsvp': $('[name=rsvp]').val(), 'grole': $('[name=grole]').val(), 'token': $('[name=token]').val()},
                            dataType: 'json',
                            success: function(data) {
                                //alert(data);
                            }
                        });

                        $(this).children().removeClass('glyphicon-ok').addClass('glyphicon-edit');
                        $(this).removeClass('btn-succss').addClass('btn-info');
                        $(this).parent().parent().children().children('.edit_name').addClass('hide');
                        $(this).parent().parent().children().children('.edit_gemail').addClass('hide');
                        $(this).parent().parent().children().children('.edit_rsvp').addClass('hide');
                        $(this).parent().parent().children().children('.edit_grole').addClass('hide');
                        $(this).parent().parent().children().children('.edit_token').addClass('hide');

                        $(this).parent().parent().children().children('.span_name').removeClass('hide');
                        $(this).parent().parent().children().children('.span_gemail').removeClass('hide');
                        $(this).parent().parent().children().children('.span_rsvp').removeClass('hide');
                        $(this).parent().parent().children().children('.span_grole').removeClass('hide');
                        $(this).parent().parent().children().children('.span_token').removeClass('hide');
                    }
                });
            }
        });
    }

    // expenses function
    function refresh_expense_table(eventId) {
        $('#expense-table').dataTable({
            "bDestroy": true,
            "bProcessing": true,
            "sAjaxSource": $url + 'event/expenses/get/' + eventId,
            "aoColumns": [
                {
                    "mData": "expenses_id",
                    "mRender": function(data, type, full) {
                        return '<div class="hide">' + data + '</div>';
                    }
                },
                {"mData": "exp_item"},
                {"mData": "particulars"},
                {
                    "mData": "estimated_amount",
                    "mRender": function(data, type, full) {
                        return '<div style="text-align:right">' + data + '</div>';
                    }
                },
                {
                    "mData": "actual_amount",
                    "mRender": function(data, type, full) {
                        return '<div style="text-align:right">' + data + '</div>';
                    }
                },
                {"mData": "receipt_num"},
                {"mData": "purchase_date"},
                {
                    "mData": "exp_chq",
                    "mRender": function(data, type, full) {
                        var cheque = data.split('-');
                        if (cheque[0] == 0) {
                            return '';
                        } else {
                            return '<span>' + cheque[1] + '</span>';
                        }
                    }
                },
                {"mData": "remarks"},
            ],
            "aoColumnDefs": [{
                    "bSortable": false,
                    "aTargets": [0, 8]}],
        });
    }

    $("#add-exp-btn").on("click", function() {
        $("#add-exp-drop").show();
    });

    $(".exp-btn").on("click", function() {
        $("#add-exp-drop").hide();
    });

    $('.save-exp').click(function() {
        $.ajax({
            url: $url + '/event/expenses/save',
            type: 'POST',
            data: {'exp_item': $('#exp-item').val(), 'particulars': $('#particulars').val(), 'estimated_amount': $('#estimated-amount').val(), 'actual_amount': $('#actual-amount').val(), 'receipt_num': $('#receipt-num').val(), 'exp_cheque': $('#exp-cheque').val(), 'exp_chq_no': $('#exp-chq-no').val(), 'purchase_date': $('#purchase-date').val(), 'remarks': $('#remarks').val(), 'event_id': getEID()},
            dataType: 'json',
            success: function(data) {
                if (data === 'success') {
                    refresh_expense_table(getEID());
                    post_exp_actual_amount(getEID());
                    post_balance(getEID());
                }
            }
        });
    });

    $("#exp-cheque").on("mousedown", function() {
        if ($("#exp-cheque").is(':checked')) {
            $("#exp-chq-form").hide();
        }
        else {
            $("#exp-chq-form").show();
        }
    });

    function post_event_budget(eventID) {
        $.ajax({
            url: $url + '/event/expenses/inital_budget/' + eventID,
            type: 'POST',
            dataType: 'json',
            success: function(data) {
                if (data.data === 'success') {
                    $("#estimated-budget").val("");
                    $("#estimated-budget").val(data.result);
                }
            },
            error: function() {
                alert("error");
            }
        });
    }

    function post_exp_actual_amount(eventID) {
        $.ajax({
            url: $url + '/event/expenses/actual_amount/' + eventID,
            type: 'POST',
            dataType: 'json',
            success: function(data) {
                if (data.data === 'success') {
                    $("#total-exp-amount").val("");
                    $("#total-exp-amount").val(data.result);
                }
            },
            error: function() {
                alert("error");
            }
        });
    }

    function post_balance(eventID) {
        $.ajax({
            url: $url + '/event/expenses/balance/' + eventID,
            type: 'POST',
            dataType: 'json',
            success: function(data) {

                if (data.data === 'success') {
                    $("#bal").val("");
                    $("#bal").val(data.result);
                }
            },
            error: function() {
                alert("error balance");
            }
        });
    }

    $("#export-expense").on("mousedown", function() {
        export_expense(getEID());
    });

    function export_expense(eventID) {
        $.ajax({
            url: $url + '/event/expenses/export/' + eventID,
            type: 'POST',
            dataType: 'json',
            success: function(data) {
                if (data.data === 'success') {
                    $("#exp-export-table").remove();
                    $("#exp-export").append("<div id=exp-export-table class=hide>" + data.result + "</div>");
                    exp_export_table();
                }
            },
            error: function() {
                alert("error");
            }
        });
    }

    function exp_export_table(e) {
        var a = document.createElement('a');
        var data_type = 'data:application/vnd.ms-excel';
        var table_div = document.getElementById('exp-export-table');
        var table_html = table_div.outerHTML.replace(/ /g, '%20');
        a.href = data_type + ', ' + table_html;
        a.download = $(".view-event-from-calendar").text() + ' expense.xls';
        a.click();
        e.preventDefault();
    }

    // voucher function
    function refresh_voucher_table(eventId) {
        $('#voucher-table').dataTable({
            "bDestroy": true,
            "bProcessing": true,
            "sAjaxSource": $url + 'event/voucher/get/' + eventId,
            "aoColumns": [
                {
                    "mData": "cv_id",
                    "mRender": function(data, type, full) {
                        return '<div class="hide">' + data + '</div>';
                    }
                },
                {"mData": "cv_num"},
                {"mData": "cv_desc"},
                {
                    "mData": "cv_amount",
                    "mRender": function(data, type, full) {
                        return '<div style="text-align:right">' + data + '</div>';
                    }
                },
                {
                    "mData": "cv_chq",
                    "mRender": function(data, type, full) {
                        var cheque = data.split('-');
                        if (cheque[0] == 0) {
                            return '';
                        } else {
                            return '<span>' + cheque[1] + '</span>';
                        }
                    }
                },
                {"mData": "cv_remarks"},
                {
                    "mData": "cv_status",
                    "mRender": function(data, type, full) {
                        if (data == 0) {
                            return 'Not Paid';
                        } else {
                            return 'Paid';
                        }
                    }
                },
            ],
            "aoColumnDefs": [{
                    "bSortable": false,
                    "aTargets": [0, 5]}],
        });
    }

    $("#add-cv-btn").on("click", function() {
        $("#add-cv-drop").show();
    });

    $(".cv-btn").on("click", function() {
        $("#add-cv-drop").hide();
    });

    $('.save-cv').click(function() {
        $.ajax({
            url: $url + '/event/voucher/save',
            type: 'POST',
            data: {'cv_num': $('#cv-num').val(), 'cv_desc': $('#cv-desc').val(), 'cv_amount': $('#cv-amount').val(), 'cv_cheque': $('#cv-cheque').val(), 'cv_chq_no': $('#cv-chq-no').val(), 'cv_remarks': $('#cv-remarks').val(), 'cv_status': $('#cv-status').val(), 'event_id': getEID()},
            dataType: 'json',
            success: function(data) {
                if (data === 'success') {
                    refresh_voucher_table(getEID());
                    post_cv_amount(getEID());
                }
            }
        });
    });

    $("#cv-cheque").on("mousedown", function() {
        if ($("#cv-cheque").is(':checked')) {
            $("#cv-chq-form").hide();
        } else {
            $("#cv-chq-form").show();
        }
    });

    function post_cv_amount(eventID) {
        $.ajax({
            url: $url + '/event/voucher/amount/' + eventID,
            type: 'POST',
            dataType: 'json',
            success: function(data) {
                if (data.data === 'success') {
                    $("#total-cv-amount").val("");
                    $("#total-cv-amount").val(data.result);
                }
            },
            error: function() {
                alert("error");
            }
        });
    }

    function exp_export_table(e) {
        var a = document.createElement('a');
        var data_type = 'data:application/vnd.ms-excel';
        var table_div = document.getElementById('exp-export-table');
        var table_html = table_div.outerHTML.replace(/ /g, '%20');
        a.href = data_type + ', ' + table_html;
        a.download = $('.view-event-from-calendar').text() + ' expense.xls';
        a.click();
        e.preventDefault();
    }

    $("#export-voucher").on("mousedown", function() {
        export_voucher(getEID());
    });

    function export_voucher(eventID) {
        $.ajax({
            url: $url + '/event/voucher/export/' + eventID,
            type: 'POST',
            dataType: 'json',
            success: function(data) {
                if (data.data === 'success') {
                    $("#cv-export-table").remove();
                    $("#cv-export").append("<div id=cv-export-table class=hide>" + data.result + "</div>");
                    cv_export_table();
                }
            },
            error: function() {
                alert("error");
            }
        });
    }

    function cv_export_table(e) {
        var a = document.createElement('a');
        var data_type = 'data:application/vnd.ms-excel';
        var table_div = document.getElementById('cv-export-table');
        var table_html = table_div.outerHTML.replace(/ /g, '%20');
        a.href = data_type + ', ' + table_html;
        a.download = $('.view-event-from-calendar').text() + ' expense.xls';
        a.click();
        e.preventDefault();
    }
});
